symfony - fos 用户 : allow route to many roles even if user have just one role

标签 symfony security authorization fosuserbundle roles

在我的 symfony 项目中,使用 FOS 包,我有 4 个这样的角色:

  • ROLE_USER_ONE
  • ROLE_USER_TWO
  • ROLE_USER_THREE

  • 他们无法访问相同的 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/

    相关文章:

    php - Symfony2防火墙: keep user logged through subdomains

    security - IHTMLTxtRange.execCommand(“Copy”,false,null)由于IE设置而失败

    Perl 网络服务(服务器)最佳实践

    security - JACC 提供程序如何使用其部署的服务器的主体到角色映射功能?

    c# - 我怎样才能保护字符串,例如C#

    ruby-on-rails - 在 Doorkeeper 覆盖布局中访问 c​​urrent_user

    mysql - Doctrine 返回错误为 "eq",没有返回错误为 "in"

    php - 如何在 Symfony 2 中管理大型初始应用程序数据

    php - twig 中有任何 {addslashes} 函数吗?

    javascript - 这可以被视为安全漏洞吗?