laravel 使会话过期重定向回登录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34443632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:12:41  来源:igfitidea点击:

Make session expiration redirect back to login?

laravellaravel-4laravel-5laravel-5.1laravel-routing

提问by Sumit

When user logs in and is authenticated, I use Auth::user()->username;to show username of user on dashboard. However, for some reason when session expires the class Authdoesn't seem to work and dashboard page throws error as trying to get property of non-objectfor Auth::user()->username;. How can I redirect the user back to the login page when he clicks any link or refreshes the page after the session has expired?

当用户登录并通过身份验证时,我使用Auth::user()->username;在仪表板上显示用户的用户名。然而,当会话过期类的某种原因,Auth似乎没有工作和仪表板页面抛出错误作为trying to get property of non-objectAuth::user()->username;。当用户单击任何链接或会话过期后刷新页面时,如何将用户重定向回登录页面?

I tried the Authenticate.php middleware but it always redirects back to login page,whatever you put the credentials either correct or incorrect.However,when I don't use this middleware it logins the user.Am I missing something?

我尝试了 Authenticate.php 中间件,但它总是重定向回登录页面,无论您输入的凭据正确或不正确。但是,当我不使用此中间件时,它会登录用户。我错过了什么吗?

Route.php

路由.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',
]);

Authenticate.php:

验证.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);
    }

}

采纳答案by Chaudhry Waqas

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class. So, to protect every route from being accessed without authentication do this

如果您希望在对应用程序的每个 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
    ];

it will redirect the user if not logged in. UPDATEKeep in mind that adding authmiddleware as global will create redirect loop so avoid it.

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

如果未登录,它将重定向用户。UPDATE请记住,将auth中间件添加为全局将创建重定向循环,因此请避免它。

或者,如果您希望保护特定路由,则将中间件附加auth到该路由

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

I think you are not attaching the auth middleware to your routes.

我认为您没有将 auth 中间件附加到您的路线上。

回答by Dwain B

All you have to do is just put this constructor at the top of the controller for your dashboard. It seems Laravel has a middleware that handles this already. At least I can confirm from 5.4 and up.

您所要做的就是将此构造函数放在仪表板的控制器顶部。似乎 Laravel 已经有一个中间件来处理这个问题。至少我可以从 5.4 及更高版本确认。

public function __construct()
{
    $this->middleware('auth');
}

回答by Meta Pakistani

Create a middleware like this

像这样创建一个中间件

<?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);
    }
}

Then Group the routes and protect them like this

然后将路由分组并像这样保护它们

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

Offcourse, in the routes you have to specify your links etc, it will only allow the user when he is authenticated and if not then login page will be shown

Offcourse,在你必须指定你的链接等的路由中,它只允许用户在他通过身份验证时,如果没有,则将显示登录页面

回答by Ajay

If session is expire then you can redirect to login like as open this file app/Exceptions/Handler.php add this code

如果会话已过期,则您可以像打开此文件一样重定向到登录 app/Exceptions/Handler.php 添加此代码

    {
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {

            return redirect('/login');

        }

        return parent::render($request, $exception);
    }

回答by Dee

To make session redirect to your login just add ->middleware('auth') in your router files as shown below I am using laravel 5.3

要将会话重定向到您的登录名,只需在路由器文件中添加 ->middleware('auth') ,如下所示,我使用的是 laravel 5.3

Ex:- Route::post('controllerName','folderName\fileName@fnNmae')->middleware('auth');

例如:- Route::post('controllerName','folderName\fileName@fnNmae')->middleware('auth');

Or visit https://laravel.com/docs/5.3/authentication

或访问https://laravel.com/docs/5.3/authentication