I simply want that if admin user or front end user try to access login page even after logged in
/admin/login (admin user)
OR
/login (front end user)
then they should be redirected back to their related home page like /admin
or /
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.php namespace 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.yml services: 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.yml firewalls: main: pattern: ^/ form_login: success_handler: authentication.handler.login_success_handler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With