【问题标题】:Using client credentials middleware for all API requests对所有 API 请求使用客户端凭据中间件
【发布时间】:2018-05-20 22:00:24
【问题描述】:

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

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

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

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

绕过auth:api中间件并用Laravel\Passport\Http\Middleware\CheckClientCredentials替换它有什么问题吗?

【问题讨论】:

    标签: laravel oauth-2.0 authorization laravel-passport


    【解决方案1】:

    一个明显的大缺点是客户端凭据在 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 的一个实例。因此,即使使用带有指定 user_id 的 oauth 客户端,仅使用客户端凭据中间件也不是拥有一组路由的好解决方案。

    【讨论】:

    • FWIW 我能够通过子类化 League\OAuth2\Server\Grant\AbstractGrant 和 Passports 服务提供商注册 my ClientCredentialsGrant 而不是 League 的 here's a gist 来解决这个问题,尽管这确实限制了我对原始代码的任何更新。
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2018-04-13
    • 1970-01-01
    • 2021-05-29
    • 2020-01-10
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多