设置Laravel中的最大登录时间

huangapple go评论61阅读模式
英文:

Setting maximum logged in time in Laravel

问题

我搜索过但找不到设置活动会话超时的方法。
我正在使用Laravel 10,并且使用cookie会话驱动程序,因为有多个服务器。我想通过两个因素来控制会话时间:

  1. 如果用户在30分钟内没有活动,则会话超时。为此,我在.env文件中设置了SESSION_LIFETIME为30。
  2. 无论用户是否活动,都会话超时1小时。

我不知道是否有任何设置来管理第二个条件,还是我需要自己存储登录时间并在每个请求上进行检查。
感谢任何帮助、提示或想法。

英文:

I searched but could not find a way to set a timeout for the active session.<br>
I'm using Laravel 10 and using the cookie session driver since there are multiple servers. I want to control the session time with by 2 factors:

  1. A session timeout if the user is inactive for 30 minutes. For this
    I'm setting SESSION_LIFETIME in the .env to 30
  2. A session timeout of 1 hour irrespective of the user being active or inactive

I do not have any idea if there is any setting to manage the second condition as well or I need to manage it myself by storing the logged in time and checking it on every request.
Any help, hint or idea is appreciated.

答案1

得分: 1

config/session.php 中,您可以添加:

'lifetime' => 30 // 确定会话在最后活动后保持活动状态的时间。

并设置cookie:

'cookie' => [
    'lifetime' => 60 // 确定会话在用户关闭浏览器或不关闭浏览器时保持活动状态的时间
英文:

In config/session.php you can add:

&#39;lifetime&#39; =&gt; 30 // determines how long a session will remain active after the last activity.

And set the cookie:

&#39;cookie&#39; =&gt; [
    &#39;lifetime&#39; =&gt; 60 // determines the time the session is active regardless if the user closes the browser or not

答案2

得分: 0

我找不到任何设置,所以我自己通过重写Authenticate中间件类的handle()方法来实现。

class Authenticate extends Middleware
{
    public function handle($request, Closure $next, ...$guards)
    {
        $loginTime = new Carbon(Auth::user()->login_at);
        if ($loginTime->addHour() < now())
            return redirect('/logout');
        return parent::handle($request, $next, $guards);
    }
}
英文:

I could not find any setting so implemented on my own by overriding the handle() method of the Authenticate middleware class

class Authenticate extends Middleware
{
    public function handle($request, Closure $next, ...$guards)
    {
        $loginTime=new Carbon(Auth::user()?-&gt;login_at);
        if($loginTime-&gt;addHour()&lt;now())
            return redirect(&#39;/logout&#39;);
        return parent::handle($request, $next, $guards);
    }
}

huangapple
  • 本文由 发表于 2023年6月15日 15:29:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定