I'm working on a Symfony 2.7 project and I'd like to redirect users on a specific page if their session expires. I created a Listener that checks roles and routes and if a user is trying to access an authenticated route without being authenticated i redirect to the specific page. This is not working for the moment because the default redirection to homepage has an higher priority.
This is the listener:
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
class UserDisconnectionListener
{
protected $router;
protected $security;
protected $tokenStorage;
public function __construct(Router $router, AuthorizationChecker $security, TokenStorage $tokenStorage)
{
$this->router = $router;
$this->security = $security;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$loggedRoutes = ['user_account', 'user_index', '...'];
$url = '';
if($this->tokenStorage->getToken() !== null) {
if(!$this->security->isGranted('IS_AUTHENTICATED_OPENID')) {
if (in_array($request->get('_route'), $loggedRoutes)) {
$url = $this->router->generate('disconnection_route');
}
}
if(strlen($url) > 0) {
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
}
app.userroute.listener:
class: app\UserBundle\Listener\UserDisconnectionListener
arguments: ['@router.default', @security.authorization_checker, @security.token_storage]
scope: request
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Is there a better way to do it ? I tried to use priority tag but i don't which priority set. I tried to log and when i tried to access 'user_index' route my listerner log said that i was already redirected on the homepage 'general_index' route.
PS: I'm using FOSUserBundle coupled with an OpenID Bundle.