How to log users off automatically after a period of inactivity?

后端 未结 9 1871
心在旅途
心在旅途 2020-11-27 03:21

After a lot of search in the web and find nothing, I wonder if there is an easy way to automatic logout the user logged through the Symfony Security after an inactive period

9条回答
  •  心在旅途
    2020-11-27 04:02

    You have to implement it with a kernel listener, this is the way I solve it:

    Listener src/Comakai/MyBundle/Handler/SessionIdleHandler.php

    namespace Comakai\MyBundle\Handler;
    
    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;
    
    class SessionIdleHandler
    {
    
        protected $session;
        protected $securityToken;
        protected $router;
        protected $maxIdleTime;
    
        public function __construct(SessionInterface $session, TokenStorageInterface $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')));
                }
            }
        }
    
    }
    

    Config src/Comakai/MyBundle/Resources/config/services.yml (Comakai/MyBundle/DependencyInjection/MyBundleExtension.php)

    services:
        my.handler.session_idle:
            class: Comakai\MyBundle\Handler\SessionIdleHandler
            arguments: ["@session", "@security.context", "@router", %session_max_idle_time%]
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    

    Now you can set the session_max_idle_time in parameters.yml to 30 * 60 = 1800 seconds (or just hardcode the value wherever you want):

    Parameters app/config/parameters.yml

    parameters:
        ...
        session_max_idle_time: 1800
    

提交回复
热议问题