Skip to content
Advertisement

How to make /login route accessible only for anonymous users in Symfony4?

My access_controll looks like:

- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY}
- { path: ^/, roles: ROLE_USER}

I need to give an access to route /login only to anonymously authenticated users.

Advertisement

Answer

Okay, there’s a better variant to do this even with redirect. Firstable, you need to edit security.yaml with this:

access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY}
        - { path: ^/, roles: ROLE_USER}

And then just add this to your SecurityController::login() method:

if ($this->isGranted('ROLE_USER')) {
        return new RedirectResponse(
            $this->generateUrl('index')
        );
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement