如何检查未登录的用户是否具有角色? [英] How can I check if a non-logged in user has a role?
问题描述
我遇到一种情况,需要检查未登录用户的角色.
I have a situation where I need to check the roles for a user who isn't logged in.
我最初只是查询 users
表的 roles
字段以查看是否包含有问题的角色,但这并没有考虑角色层次结构.例如,如果用户已被授予 ROLE_ADMIN
,他们还将拥有 ROLE_USER
.但是,您不会在数据库中看到 ROLE_USER
,因为在这种情况下,它包含在 ROLE_ADMIN
中.
I was originally simply querying the users
table's roles
field to see if the role in question was contained, but this does not take into account role heirarchy. For example, if a user has been granted ROLE_ADMIN
they would also have ROLE_USER
. However, you won't see ROLE_USER
in the database, since in this case it's included in ROLE_ADMIN
.
我对 Symfony2 安全机制的内部工作有点不熟悉 - 我想可能为用户模拟"一个令牌(基于他们的用户名),但我不知道如何做,或者如果它是甚至可能.我一直在研究安全组件,但还没有找到解决方案.
I'm a bit unfamiliar with the inner workings of Symfony2's security mechanism - I'd like to possibly "mock" a token for a user (based on their username) but I'm not sure how to, or if it's even possible. I've been digging around the Security component, but haven't found a solution yet.
是否可以检查未登录用户的角色?
Is it possible to check the roles of a user that is not logged in?
推荐答案
要获取用户拥有的角色列表,请查看此代码
To get the list of roles users have, have a look at this code
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
//....
$roleHierarchy = new RoleHierarchy($this->container->getParameter('security.role_hierarchy.roles'));
$userRoles = array(new Role('ROLE_ADMIN')); // Or $securityContext->getToken()->getRoles()
$reachableRoles = $roleHierarchy->getReachableRoles($userRoles);
这篇关于如何检查未登录的用户是否具有角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!