代码之家  ›  专栏  ›  技术社区  ›  Jeff Lambert

对所有API请求使用客户端凭据中间件

  •  3
  • Jeff Lambert  · 技术社区  · 7 年前

    在我的 routes/api.php 文件,我有一个这样的路由组:

    Route::group([
        'prefix' => config('api.route_prefix'),
        'middleware' => ['api', 'auth:api'],
    ], function() {
    // ...
    

    这仅允许通过密码检索令牌的用户授予访问这些路由的权限。在尝试实现客户端凭据授予时,我发现 separate middleware is necessary . 自 auth:api 中间件引发了一个异常,这导致了冲突,因为我希望具有任何一种授予类型的有效令牌的请求访问这些路由。

    我发现,仅使用客户端凭据中间件似乎可以验证两者,但我不确定这样做是否有任何不良影响。

    绕过 认证:api 中间件并将其替换为 Laravel\Passport\Http\Middleware\CheckClientCredentials ?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jeff Lambert    7 年前

    一个明显的大缺点是客户端凭据在JWT令牌中似乎没有任何用户信息。这会导致请求的用户解析器在调用时返回null request()->user() . 从…起 Laravel\Passport\Guards\TokenGuard::authenticateViaBearerToken ,这是返回的 null :

    // If the access token is valid we will retrieve the user according to the user ID
    // associated with the token. We will use the provider implementation which may
    // be used to retrieve users from Eloquent. Next, we'll be ready to continue.
    $user = $this->provider->retrieveById(
        $psr->getAttribute('oauth_user_id')
    );
    

    跟踪 $psr->getAttribute 引导我 League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::validateAuthorization :

     // Return the request with additional attributes
    return $request
        ->withAttribute('oauth_access_token_id', $token->getClaim('jti'))
        ->withAttribute('oauth_client_id', $token->getClaim('aud'))
        ->withAttribute('oauth_user_id', $token->getClaim('sub'))
        ->withAttribute('oauth_scopes', $token->getClaim('scopes'));
    

    所有属性 除了 oauth_user_id 通过令牌上的声明正确设置, $token 在我的例子中是 Lcobucci\JWT\Token . 因此,仅使用客户端凭据中间件并不是拥有单个路由集的好解决方案,即使使用具有指定路由的oauth客户端 user_id .