denyAccessUnlessGranted在控制器中的多个角色

时间:2016-01-12 15:58:57

标签: php symfony roles

我发现这种控制器方法有助于使用角色名称过滤访问权限:

$this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

是否可以对多个角色使用相同的方法。我试过这样的东西,但似乎没有用:

$this->denyAccessUnlessGranted(array('ROLE_EDIT', 'ROLE_WHATEVER'), $item, 'You cannot edit this item.');

感谢您的帮助

2 个答案:

答案 0 :(得分:6)

查看方法显示它是如何工作的

protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
{
    if (!$this->isGranted($attributes, $object)) {
        throw $this->createAccessDeniedException($message);
    }
}

因此您可以轻松地将其与您的案例相匹配

在控制器中

喜欢:

if(!$this->isGranted('ROLE_EDIT', $item) && !$this->isGranted('ROLE_OTHER', $item)){
    throw $this->createAccessDeniedException('not allowed');
}

答案 1 :(得分:5)

denyAccessUnlessGranted接受一系列角色名称,所以

$this->denyAccessUnlessGranted(['ROLE_EDIT', 'ROLE_ADMIN'], $item, 'You cannot edit this item.');

所以,你应该能够传递你的所有角色。

克雷格

相关问题