How can I check if a non-logged in user has a role?

别来无恙 提交于 2019-12-22 18:22:13

问题


I have a situation where I need to check the roles for a user who isn't logged in.

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.

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?


回答1:


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);


来源:https://stackoverflow.com/questions/9539559/how-can-i-check-if-a-non-logged-in-user-has-a-role

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!