'Laravel 5.3 + Passport: always unauthenticated error
I'm always receiving "Unauthenticated error" when using Passport in my current project. That's what I did the lasts 3 days:
- Install and configure Passport (as docs says)
- Request a token (password grant token) with Postman
- Request a protected route (auth:api middleware) with the token
- Get `{ "error": "Unauthenticated." }`
- Search and search and research
- Get `{ "error": "Unauthenticated." }`
Then, I've installed a fresh L5.3 and a fresh DB and works fine. Even with my current DB!
I've tried all the solutions that I found without success ...
Can anyone help me? Any idea would be appreciated.
Thanks.
Solution 1:[1]
I had the same problem as you and looked everywhere to find a solution.
It appeared to be Apache's fault in my case. Apache was deleting the header "Authorization: Bearer TOKEN_HERE" so the auth:api wouldn't work as expected (getting 401 unauthorized).
We ended up trying adding to our .htaccess:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
And it magically worked.
I really hope it helps, we spent a whole day trying many solutions, this is the one that worked for us.
Solution 2:[2]
Which grant_type have you used to generate this token?
Possible resolutions are as follows
1: If you are using client credentials to generate your access_token, you have to turn on client_credentials, middleware as follows.
1.1 Add to the routeMiddleware in \App\Http\Kernel.php
'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
1.2 Use 'client_credentials' middleware in your route too.
Route::group(['prefix' => 'v1','middleware' => 'client_credentials'], function () {
// Your routes here
});
2: For Grant Type Password
2.1 : Create a Password Grant Client
php artisan passport:client --password
2.2 : Request A token with following header fields
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => '[email protected]',
'password' => 'my-password',
End point /oauth/token
The token you get now should give you access to your api.
Solution 3:[3]
My problem was an omision, I'm building a GraphQL api and in the middleware line at the configuration file "graphql.php" I put
'middleware' => ['auth'],
when the correct way is:
'middleware' => ['auth:api'],
Solution 4:[4]
check your user model has
use Laravel\Passport\HasApiTokens;
instead of
use Laravel\Sanctum\HasApiTokens;
and used HasApiTokens as a trait;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leo Thibaudat |
| Solution 2 | Draken |
| Solution 3 | José Lozano Hernández |
| Solution 4 | Harshadeva Priyankara Bandara |
