douyuan9512 2017-03-12 15:50
浏览 140
已采纳

Symfony,允许访问所有路由,除了一个(或两个)

I'm new to Symfony 3. I'm trying to configure the routes that users and admins can access. I have two roles: ROLE_USER and ROLE_ADMIN, I've configured my security.xml as follows:

role_hierarchy:
    ROLE_ADMIN: ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN


access_control:
    - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^/, role: ROLE_USER }

I want to allow the ROLE_ADMIN users to access all routes except login. And I want to allow the ROLE_USER users to access all routes except login and admin

I'm not sure why, but it looks like all ROLE_ADMIN users also receive the ROLE_USER. And I've set the ROLE_USER to access all routes (by setting ^/ in its path) which includes the /admin and /login routes.

The question is: how can I set the path to correctly disallow ROLE_USER from accessing the /admin and /login routes?

  • 写回答

1条回答 默认 最新

  • duanmei1922 2017-03-12 16:33
    关注

    I'm not sure why, but it looks like all ROLE_ADMIN users also receive the ROLE_USER

    Well, this is the meaning of role hierarchy and you wrote it yourself ROLE_ADMIN: ROLE_USER. So, as admin have more privilege than user you can't restrict him to access user ressources.

    I don't know why you want this behavior but you can achieve it with a workaround in your controller. Something like :

    /**
     * @Route("/login", name="login")
     */
    public function loginAction()
    {
       $context = $this->container->get('security.context');
    
       $user = $context->getToken()->getUser();
    
       $admin = $context->isGranted('ROLE_ADMIN');
    
       if ( $admin ){
           //hey I'm an admin, please redirect me to the correct ressource
       }
    
       if (  $user  ){ 
           //hey I'm a simple user, what do you want me to do ?
       }    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料