在我的 symfony 项目中,使用 FOS 包,我有 4 个这样的角色:
他们无法访问相同的 View ,只有一个 View 除外。这是我用于渲染 View 的 Controller :
/**
* @Security("has_role('ROLE_USER_ONE', 'ROLE_USER_TWO', 'ROLE_USER_THREE')")
* @Route("/add-note", name="add_user_note")
* @Method({"GET"})
*/
public function addNoteToUserAction()
{
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('ROLE_USER_ONE', 'ROLE_USER_TWO', 'ROLE_USER_THREE')) {
/* ... some persist datas and process here ... */
return $this->render('MyBundle:NoteUser:addNote.html.twig', array(
));
} else {
throw new \Exception('You have no right to access this page');
}
}
为了测试 View 渲染,我创建了一个角色为 ROLE_USER_TWO 的用户。当我呈现 View 时,出现此错误:Expression "has_role('ROLE_USER_ONE', 'ROLE_USER_TWO', 'ROLE_USER_THREE')" denied access.
据我了解,Symfony 期望用户拥有所有角色,我如何允许对用户的查看访问权限,而我的 Controller 注释和 Controller 代码中至少有这些角色之一?
最佳答案
而不是试图把每个角色都放在同一个 has_role()
语句,您必须将它们与 or
连接起来像这样:
@Security("has_role('ROLE_USER_ONE') or has_role('ROLE_USER_TWO') or has_role('ROLE_USER_THREE')")
这样,您实际上是在检查当前用户是否至少拥有这些角色中的一个,而不是所有角色。
关于symfony - fos 用户 : allow route to many roles even if user have just one role,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763472/