denyAccessUnlessGranted在控制器中有多个角色

Pyt*_*hon 8 php roles symfony

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

$this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');
Run Code Online (Sandbox Code Playgroud)

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

$this->denyAccessUnlessGranted(array('ROLE_EDIT', 'ROLE_WHATEVER'), $item, 'You cannot edit this item.');
Run Code Online (Sandbox Code Playgroud)

感谢帮助

joh*_*ith 6

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

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

所以你可以很容易地适应你的情况

在你的控制器...... 喜欢:

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


Cra*_*ner 6

denyAccessUnlessGranted接受一组角色名称,所以

$this->denyAccessUnlessGranted(['ROLE_EDIT', 'ROLE_ADMIN'], $item, 'You cannot edit this item.');
Run Code Online (Sandbox Code Playgroud)

所以,你应该能够通过你所有的角色.

克雷格

  • 请注意,自 Symfony 4.4 以来,此功能已被弃用。 (5认同)