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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34089905/
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-08-25 23:44:41  来源:igfitidea点击:

Laravel - How to redirect to login if user is not authenticated

phplaravelauthenticationlaravel-5laravel-5.1

提问by Caio Kawasaki

I'm trying to use the __constructorfrom the extended class (AdminControllerextends AdminBaseController) but aparently it's not working and I have no idea of what can be, here you can see both of my classes:

我正在尝试使用__constructor来自扩展类(AdminControllerextends AdminBaseController)但显然它不起作用,我不知道可以是什么,在这里您可以看到我的两个类:

AdminBaseController.php

AdminBaseController.php

class AdminBaseController extends Controller
{
    public function __construct(){
        if (!Auth::user()){
            return view('admin.pages.login.index');
        }
    }
}

AdminController.php

管理控制器.php

class AdminController extends AdminBaseController
{
    public function __construct(){
        parent::__construct();
    }

    public function index()
    {
        return view('admin.pages.admin.index');
    }

    public function ajuda()
    {
        return view('admin.pages.admin.ajuda');
    }
}

EDIT

编辑



This is my adminroute group:

这是我的admin路线组:

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

    Route::get('login', 'Admin\AuthController@getLogin');
    Route::post('login', 'Admin\AuthController@postLogin');
    Route::get('logout', 'Admin\AuthController@getLogout');

    Route::group(['prefix' => 'configuracoes'], function () {
        Route::get('geral', 'Admin\AdminConfiguracoesController@geral');
        Route::get('social', 'Admin\AdminConfiguracoesController@social');
        Route::get('analytics', 'Admin\AdminConfiguracoesController@analytics');
    });

    Route::get('ajuda', 'Admin\AdminController@ajuda');
});

回答by Moppo

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

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

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

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

First of all get rid of your AdminBaseControllerand use only AdminController

首先摆脱你的AdminBaseController并且只使用AdminController

Then you have to check that the authmiddleware is enabled in the file app\Http\Kernel.php

然后你必须检查auth文件中是否启用了中间件app\Http\Kernel.php

You should have the line:

你应该有这条​​线:

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

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

这意味着中间件处于活动状态并可用于您的路由。

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

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

//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');
});

回答by Denis

Use middleware for this purpose and then in controller constructor use it as in example below.

为此目的使用中间件,然后在控制器构造函数中使用它,如下例所示。

public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}

And then you need to secure routes where you want from user to be logged in to access.

然后您需要保护您希望用户登录访问的路由。

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

回答by Bruce Tong

In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationExceptionexception.

在 Laravel 5.5 中,未经身份验证的用户将导致 Authenticate 中间件抛出AuthenticationException异常。

protected function authenticate(array $guards)
{
 if (empty($guards))
 {
  return $this->auth->authenticate();
 }
 foreach ($guards as $guard) {
  if ($this->auth->guard($guard)->check()) {
      return $this->auth->shouldUse($guard);
  }
 }
 throw new AuthenticationException('Unauthenticated.', $guards);
}

This will be caught by the app/Exceptions/Handler class which will call its rendermethod which is responsible for converting a given exception into a HTTP response.

这将被 app/Exceptions/Handler 类捕获,该类将调用其render负责将给定异常转换为 HTTP 响应的方法。

public function render($request, Exception $exception)
{
 return parent::render($request, $exception);
}

App/Exceptions/Handler extends 'Illuminate\Foundation\Exceptions\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. It has its own render method. Within that render method, there's a if elsestatement that says.

App/Exceptions/Handler 扩展了 'Illuminate\Foundation\Exceptions\Handler',位于 '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler' 内。它有自己的渲染方法。在那个渲染方法中,有一个if else声明说。

elseif ($e instanceof AuthenticationException)
{
 return $this->unauthenticated($request, $e);
}

Below is the ‘unauthenticated‘ method that is called by the above within the same class

下面是上面在同一类中调用的“未经身份验证”方法

protected function unauthenticated($request, AuthenticationException $exception)
{
  return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));
}

within this method is where you redirect an unauthenticated user.

在此方法中,您可以重定向未经身份验证的用户。

As far as I can see, this is what goes on behind the scenes.

据我所知,这就是幕后发生的事情。

回答by zt1983811

The way you extends and execute the parent constrictor is right, however returning a view to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send().

您扩展和执行父约束的方式是正确的,但是返回执行它的视图只能从路由、控制器操作和过滤器中返回。否则你必须调用send()。

for you purpose I think you should use before for filter http://laravel.com/docs/4.2/routing#route-filters

为了您的目的,我认为您应该在过滤器之前使用http://laravel.com/docs/4.2/routing#route-filters