gpt4 book ai didi

session - 如何在一段时间不活动后自动注销用户?

转载 作者:行者123 更新时间:2023-12-03 13:03:41 27 4
gpt4 key购买 nike

在网络上进行大量搜索后,一无所获,我想知道是否有一种简单的方法可以在非事件期后自动注销通过 Symfony Security 登录的用户。例如,我希望用户在 30 分钟不活动后注销。

我使用自定义用户提供程序,例如 this .

但用户登录系统后, session 永不过期。即使他关闭浏览器并在几天后再次打开它, session 仍然有效。

无论如何可以通过自动方式甚至手动方式注销该用户?
我怎样才能做到这一点?

最佳答案

您必须使用内核监听器来实现它,这是我解决它的方法:

听众 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')));
}
}
}

}

配置 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 }

现在您可以设置 session_max_idle_time参数.yml 到 30 * 60 = 1800 秒(或者只是硬编码任何你想要的值):

参数 应用程序/配置/参数.yml
parameters:
...
session_max_idle_time: 1800

关于session - 如何在一段时间不活动后自动注销用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18872721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com