小心...
在涉及到安全性时要非常小心。不要这样做THIS。
这是因为,您需要了解TokenInterface 与UserInterface 不同。
TokenInterface 是用户认证的接口
信息。
您必须使用它 - 如果您当前的服务中没有可用的令牌,请使用 SecurityContext 或 AccessDecisionManager。
注意:在 Symfony > 2.6 中,创建了一些 improvements,而 SecurityContext 已弃用,并分为 TokenStorage 和 AuthorizationChecker。所以,你现在可以继续使用AuthorizationChecker。
看!甚至 FOSUserBundle implementation 都在谈论它:
/**
* Never use this to check if this user has access to anything!
*
* Use the SecurityContext, or an implementation of AccessDecisionManager
* instead, e.g.
*
* $securityContext->isGranted('ROLE_USER');
*
* @param string $role
* @return Boolean
*/
function hasRole($role);
看看它是如何工作的,比如getRoles、Hierarchical roles。
数据库中的角色不可信 - 如果您从数据库中获取用户对象,并使用您的 getRoles() 或更糟糕的是您创建的特殊 isGranted($role),他们将不会拥有您期望的角色用户拥有。
This 应该是你的圣经,现在你可以理解它们之间的区别了:
1 $user->getRoles()
array(2) {
[0]=> string(10) "ROLE_ADMIN"
[1]=> string(9) "ROLE_USER"
}
2 $this->token->getRoles()
array(2) {
[0]=> object(Symfony\Component\Security\Core\Role\Role)
(1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(10) "ROLE_ADMIN" }
[1]=> object(Symfony\Component\Security\Core\Role\Role)
(1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(22) "ROLE_ALLOWED_TO_SWITCH" }
[2]=> object(Symfony\Component\Security\Core\Role\Role)
(1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(9) "ROLE_USER" }
}
3 $this->token->getUser->getRoles()
array(2) {
[0]=> string(10) "ROLE_ADMIN"
[1]=> string(22) "ROLE_ALLOWED_TO_SWITCH"
[2]=> string(9) "ROLE_USER"
}
当你有 security.yml
security:
role_hierarchy:
ROLE_ADMIN: [ROLE_ALLOWED_TO_SWITCH]