且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel-如果用户未通过身份验证,如何重定向到登录

更新时间:2021-09-15 08:04:22

控制器不是检查用户是否已通过身份验证的正确位置.您应该为此使用中间件.要获取有关什么是中间件的信息,请在此处

The controller is not the right place to check if a user is authenticated or not. You should use a middleware for that. To get info on what a middleware is check here

让我们看看如何为此目的使用默认的Laravel的auth中间件:

Let's see how you can use the default Laravel's auth middleware for this purpose:

首先摆脱您的AdminBaseController,仅使用AdminController

First of all get rid of your AdminBaseController and use only AdminController

然后,您必须检查app\Http\Kernel.php

您应该有以下一行:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,

这意味着中间件对于您的路由是活动的且可用的.

This means that the middleware is active and usable for your routes.

现在让我们进入app\Http\Middleware\Authenticate.php中的中间件类,以指定中间件的行为:

Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :

//this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
    //check here if the user is authenticated
    if ( ! $this->auth->user() )
    {
        // here you should redirect to login 
    }

    return $next($request);
}

现在剩下要做的就是确定应该应用中间件的路由.假设您有两条只希望通过身份验证的用户可以访问的路由,则应指定以这种方式将中间件用于这两条路由:

Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:

Route::group( ['middleware' => 'auth' ], function()
{
    Route::get('admin/index', 'AdminController@index');
    Route::get('admin/ajuda', 'AdminController@ajuda');
});