leoap
leoap

Reputation: 1729

Symfony, allow access to all routes, except one (or two)

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?

Upvotes: 1

Views: 1930

Answers (1)

mickdev
mickdev

Reputation: 2885

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 ?
   }    
}

Upvotes: 4

Related Questions