使会话到期重定向回登录?
Posted
技术标签:
【中文标题】使会话到期重定向回登录?【英文标题】:Make session expiration redirect back to login? 【发布时间】:2016-03-30 08:35:31 【问题描述】:当用户登录并通过身份验证时,我使用Auth::user()->username;
在仪表板上显示用户的用户名。但是,由于某种原因,当会话到期时,Auth
类似乎不起作用,并且仪表板页面会抛出错误,如 trying to get property of non-object
for Auth::user()->username;
。当用户单击任何链接或在会话过期后刷新页面时,如何将用户重定向回登录页面?
我尝试了 Authenticate.php 中间件,但它总是重定向回登录页面,无论您输入正确或错误的凭据。但是,当我不使用此中间件时,它会登录用户。我错过了什么吗?
Route.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/*
Actions Handled By Resource Controller
Verb Path Action Route Name
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/photo show photo.show
GET /photo/photo/edit edit photo.edit
PUT/PATCH /photo/photo update photo.update
DELETE /photo/photo destroy photo.destroy
Adding Additional Routes To Resource Controllers
If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:
Route::get('photos/popular', 'PhotoController@method');
Route::resource('photos', 'PhotoController');
*/
// Display all SQL executed in Eloquent
// Event::listen('illuminate.query', function($query)
//
// var_dump($query);
// );
define('ADMIN','admin');
define('SITE','site');
Route::group(['namespace' => ADMIN], function ()
Route::get('/','UserController@showLogin');
);
////////////////////////////////////Routes for backend///////////////////////////////////////////////////
Route::group(['prefix' => ADMIN,'middleware' => 'auth'], function ()
Route::group(['namespace' => ADMIN], function ()
//Route::get('/','EshopController@products');
//sumit routes for user registration
//Route::resource('users','UserController');
Route::get('/users/destroy/id','UserController@destroy');
Route::get('UserProf','UserController@userProf');
Route::get('users','UserController@index');
Route::get('/users/create','UserController@create');
Route::get('/users/adminEdit/id','UserController@adminEdit');
Route::post('/users/adminUpdate','UserController@adminUpdate');
Route::post('/users/store','UserController@store');
Route::get('/users/edit/id','UserController@edit');
Route::post('/users/update/id','UserController@update');
//airlines route
Route::get('airlines','AirlinesController@index');
Route::get('/airlines/create','AirlinesController@create');
Route::post('/airlines/store','AirlinesController@store');
Route::get('/airlines/edit/id','AirlinesController@edit');
Route::post('/airlines/update','AirlinesController@update');
Route::get('/airlines/destroy/id','AirlinesController@destroy');
//end sumit routes
//flight routes
Route::get('flights','FlightController@index');
Route::get('showFlightBook','FlightController@showFlightBook');
Route::get('flights/create','FlightController@create');
Route::post('flights/store','FlightController@store');
Route::get('flights/book','FlightController@book');
Route::get('flights/edit/id','FlightController@edit');
Route::post('flights/update','FlightController@update');
Route::get('flights/destroy/id','FlightController@destroy');
//Route::resource('flight','FlightController');
//hotels route
Route::get('hotels','HotelsController@index');
Route::get('/hotels/create','HotelsController@create');
Route::post('/hotels/store','HotelsController@store');
Route::get('/hotels/edit/id','HotelsController@edit');
Route::post('/hotels/update','HotelsController@update');
Route::get('/hotels/destroy/id','HotelsController@destroy');
//end sumit routes
//book-hotel routes
Route::get('hotel-book','HotelBookController@index');
Route::get('showHotelBook','HotelBookController@showHotelBook');
Route::get('hotel-book/create','HotelBookController@create');
Route::post('hotel-book/store','HotelBookController@store');
Route::get('hotel-book/book','HotelBookController@book');
Route::get('hotel-book/edit/id','HotelBookController@edit');
Route::post('hotel-book/update','HotelBookController@update');
Route::get('hotel-book/destroy/id','HotelBookController@destroy');
//Route::resource('hotel','HotelController');
//close flight routes
//for admin login
//Route::get('initlogin','UserController@lgnPage');
Route::get('login','UserController@showLogin');
// Route::get('privilegeLogin','UserController@privilegeLogin');
// Route::post('privilegeCheck','UserController@privilegeCheck');
Route::post('login','UserController@doLogin');
Route::get('/dashboard','DashController@index');
Route::get('logout','UserController@doLogout');
//user login
//Route::get('userLogin','UserController@showUserLogin');
//Route::post('userLogin','UserController@doUserLogin');
Route::get('/userDashboard','DashController@userIndex');
Route::get('Logout','UserController@doUserLogout');
//password reset
Route::get('forget-pass','UserController@showReset');
//Route::get('home', 'PassResetEmailController@index');
);
);
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
验证.php:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
$this->auth = $auth;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
if ($this->auth->guest())
if ($request->ajax())
return response('Unauthorized.', 401);
else
// return redirect()->guest('auth/login');
return redirect()->guest('/');
return $next($request);
【问题讨论】:
这应该在中间件文件Authienticate.php
中处理。请参阅此处的行: ... return redirect()->guest('auth/login');
你的routes.php
是什么样的?所有需要你登录的路由都被这个中间件分组了吗?
@TimLewis 不,它没有被分组,好的,如果通过这个 Authenticate.php
中间件进行分组路由可以工作,我会给它 try.so on return redirect()->guest('auth/login');
重定向路径应该替换为我们自己的登录页面路径是什么?
@Sumit 是的,它应该是您的登录页面路径
@TimLewis 我不知道是什么原因,当我在路由上应用 Authenticate.php 中间件时,无论我在登录页面上放置什么凭据,页面总是重定向回登录页面。用户能够登录在我使用这个中间件之前。该怎么办?
【参考方案1】:
如果您希望在对应用程序的每个 HTTP 请求期间运行中间件,只需在 app/Http/Kernel.php 类的 $middleware 属性中列出中间件类即可。 因此,为了保护每条路由不被未经身份验证访问,请这样做
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
];
如果未登录,它将重定向用户。更新请记住,将 auth
中间件添加为全局将创建重定向循环,因此请避免它。或者,如果您愿意要保护的特定路由,然后将中间件auth
附加到该路由
Route::get('admin/profile', ['middleware' => 'auth', function ()
//
]);
我认为您没有将身份验证中间件附加到您的路由。
【讨论】:
【参考方案2】:创建这样的中间件
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
$this->auth = $auth;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
if ($this->auth->guest())
if ($request->ajax())
return response('Unauthorized.', 401);
else
return redirect()->guest('login');
return $next($request);
然后将路由分组并像这样保护它们
Route::group(['middleware' => 'auth'], function()
Route::get();
Route::get();
Route::get();
Route::get();
当然,在路由中你必须指定你的链接等,它只会在用户通过身份验证时允许,如果没有,则会显示登录页面
【讨论】:
【参考方案3】:要使会话重定向到您的登录名,只需在您的路由器文件中添加->middleware('auth')
,如下所示我使用的是 laravel 5.3
例如:
Route::post('controllerName','folderName\fileName@fnNmae')->middleware('auth');
或访问https://laravel.com/docs/5.3/authentication
【讨论】:
【参考方案4】:您只需将此构造函数放在仪表板控制器的顶部即可。似乎 Laravel 已经有一个中间件可以处理这个问题。至少我可以从 5.4 及更高版本确认。
public function __construct()
$this->middleware('auth');
【讨论】:
是的,您可以将此构造函数放在使用来自 Auth 类的属性数据的所有控制器的顶部。现在会发生的是,当会话到期时,laravel 将要求用户登录,因此再次设置会话数据,然后重定向到会话到期时使用所在的页面。【参考方案5】:如果会话过期,那么您可以重定向以登录 打开这个文件 app/Exceptions/Handler.php 添加这段代码
public function render($request, Exception $exception)
if ($exception instanceof \Illuminate\Session\TokenMismatchException)
return redirect('/login');
return parent::render($request, $exception);
【讨论】:
你把它放在 Handler 的“render”方法下,对吗? Handler.php public function render($request, Exception $exception) if ($exception instanceof \Illuminate\Session\TokenMismatchException) return redirect('/login'); 返回父级::render($request, $exception);以上是关于使会话到期重定向回登录?的主要内容,如果未能解决你的问题,请参考以下文章
使Java HTTP会话无效以重定向到其他服务器,而无需将用户注销