symfony - 在 Symfony2 中如何获取用户的完整角色列表

标签 symfony security-context

我想将经过身份验证的用户角色列表传递到我的前端应用程序,以便我可以在前端和后端使用相同的访问控制结构。

我正在查找安全/身份验证类,因为这是 isGranted 函数让我执行此操作的地方

$this->container->get('security.context')->isGranted('ROLE_SUPER_ADMIN')

但是我找不到任何内容来获取角色列表,这不是受支持的功能吗?

nb:我不需要整个角色层次结构,只需要经过身份验证的用户的角色列表

最佳答案

我最终添加了一个新的存储库函数和一个服务方法来获取此信息。

MyProject/UserBundle/Entity/Repository/UserRepository

public function getRoles($userId)
{
    $queryBuilder = $this->createQueryBuilder('u');
    $queryBuilder
        ->select('u.id, u.roles AS user_roles, g.roles AS group_roles')
        ->leftJoin('u.groups', 'g')
        ->andWhere('u.id = :user_id')
        ->setParameter('user_id', $userId);

    return $queryBuilder->getQuery()->getArrayResult();
}

MyProject/UserBundle/Service/UserService

public function getUserRoles($user)
{
    $groupRoles = $this->repository->getRoles($user->getId());

    $roles = array('user_roles' => array(), 'group_roles' => array());
    foreach ($groupRoles as $groupRole) {
        $roles['user_roles'] = array_merge($roles['user_roles'], $groupRole['user_roles']);
        $roles['group_roles'] = array_merge($roles['group_roles'], $groupRole['group_roles']);
    }

    return $roles;
}

这给了我一个像这样的数组

"roles":{
    "user_roles":[],
    "group_roles":["ROLE_ADMIN","ROLE_ONE","ROLE_TWO","ROLE_BEST"]
}

关于symfony - 在 Symfony2 中如何获取用户的完整角色列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478481/

相关文章:

symfony - 使用 Symfony2 的 Behat 3,使用开发环境的 api 测试

java - Spring Security : SecurityContextHolder. getContext().getAuthentication() 在用户注册用户并重定向到登录后页面后返回 null

java - 上下文注入(inject)的 SecurityContext 为 null

sql-server - SQL 服务器 : The server principal is not able to access the database under the current security context/windows authentication for the login

symfony - 如何删除 symfony 形式的默认 ID 和名称?

symfony - 如何使用 KNP Menu Bundle 2 创建面包屑?

php - 有没有办法在 doctrine2 中使用 mysql 二元运算符?

php - Doctrine 仅返回空缓存的结果

vb.net - 在 vb.net 中以不同用户身份运行新进程

authentication - 使用Spring Security时,请求之间是否共享SecurityContext?