How to use the AccessDecisionManager in Symfony2 for authorization of arbitrary users?

后端 未结 7 1903
庸人自扰
庸人自扰 2020-12-14 21:14

I\'d like to be able to verify whether or not attributes (roles) are granted to any arbitrary object implementing UserInterface in Symfony2. Is this possible?

7条回答
  •  悲哀的现实
    2020-12-14 21:53

    You need only AccessDecisionManager for this, no need for security context since you don't need authentication.

    $user = new Core\Model\User();
    
    $token = new UsernamePasswordToken($user, 'none', 'none', $user->getRoles());
    $isGranted = $this->get('security.access.decision_manager')
        ->decide($token, array('ROLE_ADMIN'));
    

    This will correctly take role hierarchy into account, since RoleHierarchyVoter is registered by default

    Update

    As noted by @redalaanait, security.access.decision_manager is a private service, so accessing it directly is not a good thing to do. It's better to use service aliasing, which allows you to access private services.

提交回复
热议问题