Symfony2 Troubleshooting - Overriding loginAction from FOSUserBundle


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:

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

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:

  1. login_area:
  2. pattern: ^/login$
  3. context: primary_auth
  4. anonymous: ~
  5. main:
  6. pattern: ^/
  7. context: primary_auth
  8. form_login:
  9. provider: fos_userbundle
  10. csrf_provider: form.csrf_provider
  11. check_path: /login_check
  12. login_path: /login
  13. default_target_path: /
  14. always_use_default_target_path: false
  15. use_referer: true
  16. logout:
  17. path: /logout
  18. 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:

  1. // Don't let authenticated users access the login page because they don't need to.
  2. if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
  3. $url = $this->container->get('router')->generate('authenticated_user_homepage_route');
  4. return new RedirectResponse($url);
  5. }

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