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

后端 未结 9 1841
心在旅途
心在旅途 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 03:47

    In case anybody wants to implement this in Symfony 4, I've updated the answer @coma gave since security.context is depreciated, parameters.yml is now just part of app/config/service.yaml and you can just inject the other variables for the contructor. It's basically the same answer though, just tweaked to work for Symfony 4:

    Listener src/Security/SessionIdleHandler.php (or anywhere, it's mapped in the event listener below)

    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.');
    
                    // logout is defined in security.yaml.  See 'Logging Out' section here:
                    // https://symfony.com/doc/4.1/security.html
                    $event->setResponse(new RedirectResponse($this->router->generate(logout)));
                }
            }
        }
    }
    

    Parameters app/config/service.yaml

    parameters:
        ...
        session_max_idle_time: 600 // set to whatever value you want in seconds
    

    Kernel Event Listener app/config/service.yaml

    services:
        ...
        App.Handler.SessionIdle:
            class: App\Security\SessionIdleHandler
            arguments: ['%session_max_idle_time%']
            tags: [{ name: kernel.event_listener, event: kernel.request }]
    

提交回复
热议问题