FOSUserBundle redirect from login page after logged in
The easier solution is to add these two lines to your app/config/security.yml:
always_use_default_target_path & default_target_path, e.g.:
firewalls: main: pattern: ^/ form_login: provider: fos_userbundle csrf_provider: form.csrf_provider login_path: /login check_path: /login_check always_use_default_target_path: false default_target_path: /your/start/path/
Redirecting on login/logout in Symfony2 using LoginHandlers
You should implement the AuthenticationSuccessHandlerInterface
to handle the last minute decision when the login success.
Implement the AuthenticationSuccessHandlerInterface:
<?php// AcmeBundle\Security\LoginSuccessHandler.phpnamespace AcmeBundle\Security;use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\Routing\Router;class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface { protected $router; protected $authorizationChecker; public function __construct(Router $router, AuthorizationChecker $authorizationChecker) { $this->router = $router; $this->authorizationChecker = $authorizationChecker; } public function onAuthenticationSuccess(Request $request, TokenInterface $token) { $response = null; if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) { $response = new RedirectResponse($this->router->generate('backend')); } else if ($this->authorizationChecker->isGranted('ROLE_USER')) { $response = new RedirectResponse($this->router->generate('frontend')); } return $response; }}
Register your class as a service:
# app/config/services.ymlservices: authentication.handler.login_success_handler: class: AcmeBundle\Security\LoginSuccessHandler arguments: ['@router', '@security.authorization_checker']
Add a reference to your LoginSuccessHandler class in the firewall
# app/config/security.ymlfirewalls: main: pattern: ^/ form_login: success_handler: authentication.handler.login_success_handler
You can override FOSUserBundle\Controller\SecurityController and add the following code at the top of loginAction
.
use Symfony\Component\HttpFoundation\RedirectResponse;// ...public function loginAction(Request $request){ $authChecker = $this->container->get('security.authorization_checker'); $router = $this->container->get('router'); if ($authChecker->isGranted('ROLE_ADMIN')) { return new RedirectResponse($router->generate('admin_home'), 307); } if ($authChecker->isGranted('ROLE_USER')) { return new RedirectResponse($router->generate('user_home'), 307); } // ...