abeltodev
abeltodev

Reputation: 133

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:

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.

Upvotes: 1

Views: 3948

Answers (4)

check your user model has

use Laravel\Passport\HasApiTokens;

instead of

use Laravel\Sanctum\HasApiTokens;

and used HasApiTokens as a trait;

Upvotes: 0

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'],

Upvotes: 1

Mumtaz Hassan Syed
Mumtaz Hassan Syed

Reputation: 11

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.

Upvotes: 1

Leo Thibaudat
Leo Thibaudat

Reputation: 51

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.

Upvotes: 4

Related Questions