首页 > 解决方案 > 如何在laravel 5.5中会话时自动重定向到登录页面

问题描述

我有以下会话的配置config/session.php

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

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

'expire_on_close' => true,

当用户处于非活动状态 5 分钟并重定向到登录时,我已使会话过期。它适用于所有路由并将用户重定向到登录,但在会话到期后,当用户发送注销请求时它显示

 The page has expired due to inactivity.  Please refresh and try again. 

对于所有其他路线,它可以正常工作。

我应该怎么做才能解决这个问题?

注意:我已经看到以下问题。没有一个对我有用。

在 Laravel 5.5 中用户会话到期时自动重定向

在 Laravel 中检查会话超时

标签: phplaravelsession

解决方案


您可以保护通往中间件的每条路线。

protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\Authenticate',// add this line according to your namespace
];


it will redirect the user if not logged in. UPDATE Keep in mind that adding auth middleware as global will create redirect loop so avoid it.

Or if you want specific routes to be protected then attach the middleware auth to that route

Route::get('admin/profile', ['middleware' => 'auth', function () {
//
}]);

推荐阅读