简体   繁体   English

fos 用户:即使用户只有一个角色,也允许路由到多个角色

[英]fos user: allow route to many roles even if user have just one role

In my symfony project, using the FOS bundle, I have 4 roles like this:在我的 symfony 项目中,使用 FOS 包,我有 4 个这样的角色:

  • ROLE_USER_ONE ROLE_USER_ONE
  • ROLE_USER_TWO ROLE_USER_TWO
  • ROLE_USER_THREE ROLE_USER_THREE

They can't access to the same views, except for one.他们无法访问相同的视图,只有一个视图除外。 This is my controller for render the view:这是我用于渲染视图的控制器:

/**
 * @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');
  }
}

To test the view rendering, I create a user with role ROLE_USER_TWO.为了测试视图渲染,我创建了一个角色为 ROLE_USER_TWO 的用户。 And when I render the view I have this error:当我渲染视图时,出现此错误:

Expression "has_role('ROLE_USER_ONE', 'ROLE_USER_TWO', 'ROLE_USER_THREE')" denied access.表达式“has_role('ROLE_USER_ONE', 'ROLE_USER_TWO', 'ROLE_USER_THREE')”拒绝访问。

As I understand, Symfony expected the user have all the roles, how can I allow the view access to user which as at less one of these roles in my controller annotations and controller code?据我了解,Symfony 期望用户拥有所有角色,我怎样才能允许对用户的查看访问权限,而我的控制器注释和控制器代码中至少有这些角色之一?

Instead of trying to put every role into the same has_role() statement, you have to concatenate them with or like this:您不必尝试将每个角色放入同一个has_role()语句中,而是必须将它们与or像这样连接:

@Security("has_role('ROLE_USER_ONE') or has_role('ROLE_USER_TWO') or has_role('ROLE_USER_THREE')")

This way, you are actually checking that the current user has at least one of these roles instead of all of them.这样,您实际上是在检查当前用户是否至少拥有这些角色中的一个,而不是所有角色。

I suppose you're looking for role hierarchy .我想您正在寻找角色层次结构 Your configuration will be like:您的配置将类似于:

security:
    # ...

    role_hierarchy:
        ROLE_USER_ONE : ROLE_USER_BASE
        ROLE_USER_TWO : ROLE_USER_BASE
        ROLE_USER_THREE : ROLE_USER_BASE

So users with ROLE_USER_ONE role has also role ROLE_USER_BASE etc. Then, in your controller you just need to check only for ROLE_USER_BASE :因此,具有ROLE_USER_ONE角色的用户也具有角色ROLE_USER_BASE等。然后,在您的控制器中,您只需要检查ROLE_USER_BASE

/**
 * @Security("has_role('ROLE_USER_BASE')")
 * @Route("/add-note", name="add_user_note")
 * @Method({"GET"})
 */
public function addNoteToUserAction()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM