Search code examples
phpauthenticationsymfony4

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.


Solution

  • 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')
            );
        }