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

后端 未结 9 1836
心在旅途
心在旅途 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

    Here is my example with Symfony 4.

    Session was used instead of SessionInterface because this interface does not contain access to the getFlashBag() method.

    A redirection is performed on app_login and not on app_logout, otherwise the flashBag of the current session will be lost.

    $this->tokenStorage->setToken(); could be replaced by $this->tokenStorage->reset(); via the concrete class but the interface does not allow it.

    You could use this:

    maxIdleTime = (int) $maxIdleTime;
            $this->session = $session;
            $this->tokenStorage = $tokenStorage;
            $this->router = $router;
            $this->checker = $checker;
        }
    
        public function onKernelRequest(RequestEvent $event): void
        {
            if (!$event->isMasterRequest()
                || $this->maxIdleTime <= 0
                || $this->isAuthenticatedAnonymously()) {
                return;
            }
    
            $session = $this->session;
            $session->start();
    
            if ((time() - $session->getMetadataBag()->getLastUsed()) <= $this->maxIdleTime) {
                return;
            }
    
            $this->tokenStorage->setToken();
            $session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');
    
            $event->setResponse(new RedirectResponse($this->router->generate('app_login')));
        }
    
        private function isAuthenticatedAnonymously(): bool
        {
            return !$this->tokenStorage->getToken()
                || !$this->checker->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY);
        }
    }
    
    App\EventListener\SessionIdleListener:
        bind:
            $maxIdleTime: '%env(APP_SESSION_MAX_IDLE_TIME)%'
            $session: '@session'
        tags:
            - { name: kernel.event_listener, event: kernel.request }
    

提交回复
热议问题