【问题标题】:Laravel 5.7 auth behaviorLaravel 5.7 身份验证行为
【发布时间】:2023-03-14 11:08:01
【问题描述】:

我是 Laravel 的新手,几天以来一直在跟踪它的代码以了解它的行为,但无济于事。

假设我将中间件添加到这样的路由中

Route::group(["middleware" => ["web", "auth:web", "auth:custom"]], function() {
    Route::view("/about", "about");
});
  1. /about 路由是否经过 auth:web 后跟 auth:custom? 如果不是,那是什么行为?

  2. 如何创建不与auth:web 冲突的auth:custom 防护?当前的行为是,如果 auth:web 已通过身份验证,auth:custom 将遵循其状态,我怀疑它们共享相同的会话变量。

我对 Laravel 真的很陌生,这似乎是路由、身份验证和中间件的混合体。希望有人能指出我正确的方向。谢谢。

【问题讨论】:

    标签: laravel authentication middleware


    【解决方案1】:

    1 - 你的路由将使用来自App\Providers\RouteServiceProvider 的中间件。见:

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }
    

    您编写的每个中间件都将按照您定义的顺序执行。如果一个中间件发生故障,$next($request); 将不会被调用。所以下一个中间件不会被激活。

    2- 这些auth:webauth:custom 中间件是“auth 中间件”调用,但参数不同。 : 之后的所有内容都作为参数发送到中间件的处理方法。

    auth 中间件定义在App\Http\Kernel 类下$routeMiddleware var:

    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    

    这里是handle 方法:

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);
    
        return $next($request);
    }
    

    您的 'web' 或 'custom' 参数转到 ...$guards 参数。

    顺便说一句,没有预定义的“自定义”防护。您必须编写自己的自定义守卫并在config/auth.phpguards 数组下定义它:

    'guards' => [
        'web' => [ // This is the web guard (auth:web)
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [ // and this the api guard (auth:api)
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    

    然后,您可以期望 laravel auth 中间件使用您的自定义防护(如 auth:customauth:acme)进行身份验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 2019-06-14
      • 2019-04-30
      • 2019-05-18
      • 1970-01-01
      • 2019-05-03
      • 2016-05-16
      相关资源
      最近更新 更多