Laravel 5.6会话超时自动登出

3
I'm very new to Laravel framework. I am working on an app that automatically logs out the user if there is no activity for 5 minutes. I found some code on this website: https://github.com/unicodeveloper/laravel-sessiontimeout/blob/master/src/Middleware/SessionTimeout.php, but it doesn't seem to be working for me.
Here is the middleware code:
<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Session\Store;

class SessionTimeOutMiddleware
{
  /**
  * Instance of Session Store
  * @var session
  */
  protected $session;
  /**
   * Time for user to remain active, set to 300 secs( 5 minutes )
   * @var timeout
  */
  protected $timeout = 300;
  public function __construct(Store $session){
   $this->session        = $session;
   $this->redirectUrl    = 'auth/login';
   $this->sessionLabel   = 'warning';
 }
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
  */
 public function handle($request, Closure $next)
 {
   if(! $this->session->has('lastActivityTime'))
   {
     $this->session->put('lastActivityTime', time());
   }
   else if( time() - $this->session->get('lastActivityTime') > $this->getTimeOut())
   {
     $this->session->forget('lastActivityTime');
     Auth::logout();
     return redirect($this->getRedirectUrl())->with([ $this->getSessionLabel() => 'You have been inactive for '. $this->timeout/60 .' minutes ago.']);
   }
   $this->session->put('lastActivityTime',time());
   return $next($request);
 }
 /**
 * Get timeout from laravel default's session lifetime, if it's not set/empty, set timeout to 15 minutes
 * @return int
 */
 private function getTimeOut()
 {
   return  ($this->lifetime) ?: $this->timeout;
 } 
 /**
 * Get redirect url from env file
 * @return string
 */
 private function getRedirectUrl()
 {
   return  (env('SESSION_TIMEOUT_REDIRECTURL')) ?: $this->redirectUrl;
 } 
 /**
   * Get Session label from env file
   * @return string
 */
 private function getSessionLabel()
 {
   return  (env('SESSION_LABEL')) ?: $this->sessionLabel;
 }

这是config/session.php文件。

'lifetime' => env('SESSION_LIFETIME', 5),

'expire_on_close' => true,

并且在Kernel.php

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\SessionTimeOutMiddleware::class,
];

我是否漏掉了什么? 我已经做了很多研究,似乎找不到这个问题的答案。如果有人能帮助我解决这个问题,我将非常感激。


在 config/auth.php 文件中设置一个变量来检查会话注销。 - Ravindra Bhanderi
1个回答

7

在 .env 文件中将您的驱动程序设置为数据库

CACHE_DRIVER=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_ENCRYPT=false

希望这能有所帮助。

这在网页上超时了,但在移动端没有超时,我的用户在移动端登录两周后仍然保持登录状态,但网页正常工作。 - Excellent Lawrence

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接