Symfony2 Troubleshooting - Overriding loginAction from FOSUserBundle

Issue:

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:

Symfony2


Solution:

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:

        login_area:
            pattern: ^/login$
            context: primary_auth
            anonymous: ~
        main:
            pattern: ^/
            context: primary_auth
            form_login:
                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
            logout:
                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:

// Don't let authenticated users access the login page because they don't need to.
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.