Symfony2 troubleshooting – overriding loginAction from FOSUserBundle

March 30, 2014


Overrode the loginAction from FOSUserBundle and implemented logic to check if the user is fully authenticated already when they are about to land on the login page.  If they are fully authenticated, then redirect the user away from the login page, but when using the following code it was still allowing fully authenticated users to get to the login page:

if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    return $this->redirect($this->generateUrl('authenticated_user_homepage_route'));

System(s) Involved:



Security context doesn’t persist from one firewall to the other and this was something that I had missed when reading about Symfony firewalls and security context.  In order to make them persist, I decided that both firewalls can just share the same context, so I inserted the following “context” property under both firewalls in security.yml like such:

            pattern: ^/login$
            context: primary_auth
            anonymous: ~
            pattern: ^/
            context: primary_auth
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
                check_path: /login_check
                login_path: /login
                default_target_path: /
                always_use_default_target_path: false
                use_referer: true
                path: /logout
                target: /

As long as the name of the context in security.yml is set to the same, the security context will be the same across those firewalls.  In the above sample, my context is called “primary_auth”.

Back in my controller that I was using to override the loginAction in, I updated the redirect code as follows:

if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    $url = $this->container->get('router')->generate('authenticated_user_homepage_route');
    return new RedirectResponse($url);

Also, made sure to “use” Symfony\Component\HttpFoundation\RedirectResponse since I was returning a redirect response.  Tested and works.

You Might Also Like