Skip to content

Instantly share code, notes, and snippets.

@Isengo1989
Forked from marydn/LoginSuccessHandler.php
Last active November 19, 2018 18:04
Show Gist options
  • Save Isengo1989/2174afdb38e8503b0d67b99ef0aed8e6 to your computer and use it in GitHub Desktop.
Save Isengo1989/2174afdb38e8503b0d67b99ef0aed8e6 to your computer and use it in GitHub Desktop.
Custom URL redirect by role after success login on Symfony 2 using a service listener without FOSUser Bundle.
# src/Security/LoginFormAuthenticator.php
<?php
namespace App\Security;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
protected
$router,
$security;
public function __construct(Router $router, SecurityContext $security)
{
$this->router = $router;
$this->security = $security;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
if ($this->security->isGranted('ROLE_ADMIN')) {
$path = 'orders_index';
} elseif ($this->security->isGranted('ROLE_USER')) {
$path = 'users_index';
}
return new RedirectResponse($this->router->generate($path));
}
}
# src/config/services.yml
parameters:
authentication.handler.login_form_authenticator.class: App\Security\LoginFormAuthenticator
services:
login_success_handler:
class: App\Security\LoginFormAuthenticator
arguments: [doctrine.orm.entity_manager, router, security.csrf.token_manager, security.password_encoder, Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment