My problem, When session timed out, i refresh the page and then i get 500 error:
Impossible to access an attribute ("id") on a null variable.
because "id" is empty.
I want to redirect to login page, when user refreshes the page and his session has expired. How can I do it?
I falowed this How to log users off automatically after a period of inactivity?
I tried to use listener with Kernel action:
I modified TokenStorageInterface to AuthorizationChecker
Because this error:
Type error: Argument 2 passed to GE\CandidatBundle\EventListener\SessionIdleHandler::__construct() must implement interface Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface, instance of Symfony\Component\Security\Core\Authorization\AuthorizationChecker given
<?php
namespace GE\CandidatBundle\EventListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
class SessionIdleHandler
{
protected $session;
protected $securityToken;
protected $router;
protected $maxIdleTime;
public function __construct(SessionInterface $session, AuthorizationChecker $securityToken, RouterInterface $router, $maxIdleTime = 0)
{
$this->session = $session;
$this->securityToken = $securityToken;
$this->router = $router;
$this->maxIdleTime = $maxIdleTime;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {
return;
}
if ($this->maxIdleTime > 0) {
$this->session->start();
$lapse = time() - $this->session->getMetadataBag()->getLastUsed();
if ($lapse > $this->maxIdleTime) {
$this->securityToken->setToken(null);
$this->session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');
// Change the route if you are not using FOSUserBundle.
$event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
}
}
}
}
In the services.yml: I modified "@security.context" to "@security.authorization_checker"
Because the security.context service is deprecated.
my.handler.session_idle:
class: GE\CandidatBundle\EventListener\SessionIdleHandler
arguments: ["@session", "@security.authorization_checker", "@router", %session_max_idle_time%]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
In the parameters.yml:
parameters:
...
session_max_idle_time: 1800
Now when i refresh the page i get 500 error, it doesn't work.