简体   繁体   English

Laravel 中间件 - 跳过护照验证

[英]Laravel Middleware - Skip Passport Auth

We have 2 auth middlewares applied to specific routes, 'external_token' and 'auth:api'.我们有 2 个身份验证中间件应用于特定路由,“external_token”和“auth:api”。 When an external bearer token is presented we inspect it, and if all the values are good we consider the user authorized to access the requested url.当提供外部不记名令牌时,我们对其进行检查,如果所有值都正确,我们认为用户已授权访问请求的 url。

How do we process all other middlewares except passport auth?我们如何处理除护照身份验证之外的所有其他中间件?

public function handle(Request $request, Closure $next)
{
    $token = $request->header('Bearer');

    try {

        list($JWTHeader, $JWTPayload) = JWT::verify($token, JWT::TYPE_ID_EXTERNAL);

        $this->user = User::where('external_id', $JWTPayload['external_id'])->first();

        // Can we just set $this->user and process all other middlewares except auth?

    } catch (Exception $e) {

        Log::debug($e);
    }

    $response = $next($request);

    return $response;
}

Well, one thing you could do would be to set the user on the api guard, so when the auth middleware runs, it'll find the user you provided.好吧,您可以做的一件事是将用户设置在api守卫上,因此当 auth 中间件运行时,它会找到您提供的用户。 You would have to ensure that your external_token middleware runs first.您必须确保您的external_token中间件首先运行。

auth()->guard('api')->setUser($this->user);

Another option would be to convert your external_token middleware into a Laravel auth guard so that you can use the built-in auth functionality.另一种选择是将您的external_token中间件转换为 Laravel 身份验证保护,以便您可以使用内置的身份验证功能。 Then, you can protect your route with auth:api,external_token , and the auth will pass if any one of the specified guards is successful.然后,您可以使用auth:api,external_token保护您的路由,如果任何一个指定的守卫成功,则身份验证将通过。

The simplest example would be a closure request guard .最简单的例子是关闭请求守卫

In your AuthServiceProvider::boot() method:在您的AuthServiceProvider::boot()方法中:

// don't forget your "use" statements for all these classes

public function boot()
{
    // ...

    Auth::viaRequest('external_token_driver', function ($request) {
        $token = $request->header('Bearer');

        try {
            list($JWTHeader, $JWTPayload) = JWT::verify($token, JWT::TYPE_ID_EXTERNAL);

            return User::where('external_id', $JWTPayload['external_id'])->first();
        } catch (Exception $e) {
            Log::debug($e);
        }

        return null;
    });
}

In your auth.php config:在您的auth.php配置中:

'guards' => [
    // web, api, etc...

    'external_token' => [
        'driver' => 'external_token_driver',
    ],
],

NB: all untested.注意:所有未经测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM