Search code examples
symfonyfosuserbundlesymfony-security

Symfony - How to redirect the user to last page visited after login?


How to redirect the user to last page visited after login in Symfony with fosuserbundle?

In my controller, I check first if user is logged in. Then if he isn't, I redirect him to the login page. Here is the short code I used at the beginning of my controller.

$autenthicated = $this->checkAuth();
if($autenthicated==true){
  return $this->render('MainBundle:Default:home.html.twig');
}else{
  return $this->redirect($this->generateUrl('login_connect'));
}

The problem is that after the user has logged in, he is redirected to the main page instead the last page visited.

How should I redirect him to my custom login page? apparently this is not working:

return $this->redirect($this->generateUrl('login_connect'));

Solution

  • You don't have to handle the redirection to the login route by yourself.

    If you throw an AccessDeniedException in your controller, the security component will redirect you to the login page (with the page you tried to access as parameter).

    After login, the native LoginSuccessHandler will redirect you to the desired page.

    You can also use the Controller shortcut :

    $this->denyAccessUnlessGranted(['ROLE_USER']);// check your needed roles here 
    

    If you need to override the redirection logic after login, you can define a service and tell the security component to use this one to handle the redirection.

    Here is a dummy example :

    Your php service with redirection logic :
    AppBundle/Security/LoginSuccessHandler.php

    class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
    {
    
        // …
    
        /**
         * @param Request        $request
         * @param TokenInterface $token
         * @return RedirectResponse
         */
        public function onAuthenticationSuccess(Request $request, TokenInterface $token)
        {
            // your stuff 
            return new RedirectResponse($this->router->generate(‘custom_route’));
        }
    }
    

    Service configuration :

    # services.yml
    app.login_success_handler:
            public: false
            class: AppBundle\Security\LoginSuccessHandler
            arguments: ["@security.token_storage", "@router"]
    

    Configure the security component to use your custom handler :

    # security.yml 
    security:
        firewalls:
            main:
                form_login:
                    success_handler: app.login_success_handler