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

时间:2017-12-06 22:00:48

标签: laravel oauth-2.0 authorization laravel-passport

在我的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是否有任何问题?

1 个答案:

答案 0 :(得分:1)

一个明显的重大缺点是客户端凭据似乎在JWT令牌中没有任何用户信息。这会导致请求的用户解析程序为request()->user()的调用返回null。从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客户端,仅使用客户端凭据中间件也不是拥有单组路由的良好解决方案。

相关问题