Jeff Lambert
Jeff Lambert

Reputation: 24661

Using client credentials middleware for all API requests

In my routes/api.php file, I have a route group like this:

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

This correctly only allows users with tokens retrieved via password grant access to those routes. When trying to implement client credentials grant, I found that a separate middleware is necessary. Since the auth:api middleware raises an exception, this presents a conflict because I want requests with valid tokens of either grant type to access these routes.

What I found is that using just the client credential middleware seems to validate both, but I am unsure if there are any bad implications of doing so.

Is there anything wrong with circumventing the auth:api middleware and replacing it with Laravel\Passport\Http\Middleware\CheckClientCredentials?

Upvotes: 3

Views: 2135

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

One apparent big downside is that the client credentials doesn't seem to have any user information in the JWT token. This causes the user resolver for the request to return null for calls to request()->user(). From Laravel\Passport\Guards\TokenGuard::authenticateViaBearerToken, this was 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')
);

Tracing $psr->getAttribute led me to 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'));

All of the attributes except oauth_user_id were being set correctly via the claims on the token, $token in my case is an instance of Lcobucci\JWT\Token. So only using the client credentials middleware is not a good solution to having a single set of routes, even if using an oauth client with a specified user_id.

Upvotes: 1

Related Questions