如何在Symfony2中使用AccessDecisionManager来授权任意用户?

Adr*_*ter 12 php access-control symfony

我希望能够验证属性(角色)是否被授予UserInterface在Symfony2中实现的任何任意对象.这可能吗?

UserInterface->getRoles() 不适合我的需要,因为它不考虑角色层次结构,我宁愿不重新发明该部门的轮子,这就是为什么我想尽可能使用Access Decision Manager.

谢谢.

为了回应下面的Olivier解决方案,以下是我的经验:

您可以将security.context服务与isGranted方法一起使用.您可以传递第二个参数,它是您的对象.

$user = new Core\Model\User();
var_dump($user->getRoles(), $this->get('security.context')->isGranted('ROLE_ADMIN', $user));
Run Code Online (Sandbox Code Playgroud)

输出:

array (size=1)
  0 => string 'ROLE_USER' (length=9)

boolean true
Run Code Online (Sandbox Code Playgroud)

我的角色层次:

role_hierarchy:
    ROLE_USER:          ~
    ROLE_VERIFIED_USER: [ROLE_USER]
    ROLE_ADMIN:         [ROLE_VERIFIED_USER]
    ROLE_SUPERADMIN:    [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
    ROLE_ALLOWED_TO_SWITCH: ~
Run Code Online (Sandbox Code Playgroud)

我的UserInterface->getRoles()方法:

public function getRoles()
{
    $roles = [$this->isVerified() ? 'ROLE_VERIFIED_USER' : 'ROLE_USER'];

    /**
     * @var UserSecurityRole $userSecurityRole
     */
    foreach ($this->getUserSecurityRoles() as $userSecurityRole) {
        $roles[] = $userSecurityRole->getRole();
    }

    return $roles;
}
Run Code Online (Sandbox Code Playgroud)

ROLE_ADMIN必须明确分配,但即使用户刚刚创建并且尚未分配除默认值以外的任何角色,也会isGranted('ROLE_ADMIN', $user)返回,只要授予当前登录用户.这使我相信到第二个参数只是忽略的是,提供给被代替.TRUEROLE_USERROLE_ADMINisGranted()TokenAccessDecisionManager->decide()SecurityContext

如果这是一个错误,我会提交报告,但也许我还在做错什么?

dr.*_*cre 17

您只AccessDecisionManager需要这样,不需要安全上下文,因为您不需要身份验证.

$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'));
Run Code Online (Sandbox Code Playgroud)

这将正确地考虑角色层次结构,因为RoleHierarchyVoter默认情况下已注册

更新

正如@redalaana所指出的,security.access.decision_manager是一个私有服务,因此直接访问它并不是一件好事.最好使用服务别名,它允许您访问私有服务.

  • 这是最优雅的解决方案.谢谢 (2认同)

Mar*_*lho 3

security.context自 2.6 起已弃用。

使用AuthorizationChecker

$token = new UsernamePasswordToken(
     $user,
     null,
     'secured_area',
     $user->getRoles()
);
$tokenStorage = $this->container->get('security.token_storage');
$tokenStorage->setToken($token);
$authorizationChecker = new AuthorizationChecker(
     $tokenStorage,
     $this->container->get('security.authentication.manager'),
     $this->container->get('security.access.decision_manager')
);
if (!$authorizationChecker->isGranted('ROLE_ADMIN')) {
    throw new AccessDeniedException();
}
Run Code Online (Sandbox Code Playgroud)