咨询 Lumen5.4 Session 随机登出问题?
最近遇见Session随机登出的问题,经过几天的摸索(尝试 Google 社区搜索 线上调试),自身能力有限,希望能得到大家的帮助。谢谢!
问题
- 普通用户登录成功后,在固定几个页面来回切换,Session 会随机重新生成,导致登录失效。
- 重新生成的Session并不包含user.id。原有的Session 并未过期,依然有效。(打码部分是请求API)
- 前后端分离(前端 Vue.js v1.0.10 ),单独调用接口并无此问题。
图1API请求 图2 Redis缓存数据
代码运行环境及相关代码
-
运行环境:
- PHP5.6.23(cli),
- nginx 1.10.1,
- Redis server v=2.8.19,
- MySql 5.6,
- Vue.js v1.0.10
-
Session 配置:
- driver => redis,
- connection => session,
- lifetime => 120,
- expire_on_close => false,
- store => null,
- table => sessions,
- path => null,
- domain => null,
- secure => false,
- http_only => true,
- lottery => [2, 100],
-
env 配置:
- CACHE_DRIVER=redis
- QUEUE_DRIVER=redis
- SESSION_DRIVER=redis
-
bootsrap/app.php
$app->alias('session', \Illuminate\Session\SessionManager::class); $app->register(\Illuminate\Session\SessionServiceProvider::class); $app->configure('session'); $app->middleware([\Illuminate\Session\Middleware\StartSession::class]); //用户获取和设置Session $app->singleton('storage', \App\Auth\WebStorage::class);
-
WebStorage.php (此类用于登录成功后设置Session)
//获取当前用户 public function currentUser() { static $user = null; if(!empty($user)) { return $user; } $userId = app('session')->get('user.id', 0); if($userId <= 0){ return -4; } $user = new User(); $user->id = $userId; return $user; } //设置Session public function setCurrentUser(UserBase &$user) { $userId = $user->id; if($userId > 0) { app('session')->put('user.id', $userId); app('session')->put('user.isCompany', $user->type() == EnterpriseUser::USER_TYPE ? 1 : 0); return true; } return false; }
-
Auth中间件 (路由中间件 验证登录态)
public function handle($request, Closure $next, $guard = null) { $res =$this->auth->guard($guard)->user(); if ($res instanceof Error) { return response([ 'code' => $res->errCode, 'msg' => $res->errMsg, ], 200); } return $next($request); }
-
AuthServiceProvider.php
public function boot() { $this->app['auth']->viaRequest('api', function (Request $request) { $user = app('session')->get('user'); $userId = isset($user['id']) ? $user['id'] : 0; if ($userId > 0) { if(isset($user['isCompany']) && $user['isCompany'] > 0) { return new EnterpriseUser($userId); } else { return new User($userId); } } return new Error(Error::USER_NOT_LOGIN, Error::$MSG[Error::USER_NOT_LOGIN]); }); }
推荐文章: