Instantly share code, notes, and snippets.

Embed
What would you like to do?
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