对所有 API 请求使用客户端凭据中间件
Using client credentials middleware for all API requests
在我的 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
有什么问题吗?
一个明显的大缺点是客户端凭据在 JWT 令牌中似乎没有任何用户信息。这会导致请求的用户解析器对 request()->user()
的调用为 return null。来自 Laravel\Passport\Guards\TokenGuard::authenticateViaBearerToken
,这是 returning 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
在我的例子中是[=的一个实例19=]。因此,即使使用具有指定 user_id
.
的 oauth 客户端,仅使用客户端凭据中间件也不是拥有一组路由的好解决方案。
在我的 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
有什么问题吗?
一个明显的大缺点是客户端凭据在 JWT 令牌中似乎没有任何用户信息。这会导致请求的用户解析器对 request()->user()
的调用为 return null。来自 Laravel\Passport\Guards\TokenGuard::authenticateViaBearerToken
,这是 returning 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
在我的例子中是[=的一个实例19=]。因此,即使使用具有指定 user_id
.