Home » Php » php – Always got "message": "Unauthenticated." – Laravel Passport

php – Always got "message": "Unauthenticated." – Laravel Passport

Posted by: admin July 12, 2020 Leave a comment

Questions:

I had find many tutorial this whole day. And my setup is exactly the same as all the basic tutorial out there.

Currently, i’m able to access http://localhost/oauth/token with successfully return token to me.

After that, i’m using ARC (Advanced Rest Client) to do the testing of calling my own api.

I had passed header such as

Authorization: Bearer the_token_here
accept: application/json

From that header, I just wanted to access the default API provided by laravel /user.

But, I always got response of { "message": "Unauthenticated." }

Refer this tutorial https://itsolutionstuff.com/post/laravel-5-how-to-create-api-authentication-using-passport-example.html

I’m able to do login as per tutorial, but i’m unable to get data by endpoint details. It returning response of { "message": "Unauthenticated." }

My route of api.php

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
    Route::get('/user', function( Request $request ){
        return $request->user();
    });
});

By the way, there are no error message in laravel.log and i had set to Debug mode

UPDATE Thanks to Comment point out by Mayank

League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in /.../vendor/league/oauth2-server/src/Exception/OAuthServerException.php:173
Stack trace:
#0 /.../vendor/league/oauth2-server/src/AuthorizationValidators/BearerTokenValidator.php(59): League\OAuth2\Server\Exception\OAuthServerException::accessDenied('Missing "Author...')
#1 /.../vendor/league/oauth2-server/src/ResourceServer.php(82): League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator->validateAuthorization(Object(Zend\Diactoros\ServerRequest))
#2 /.../vendor/laravel/passport/src/Http/Middleware/CheckClientCredentials.php(46): League\OAuth2\Server\ResourceServer->validateAuthenticatedRequest(Object(Zend\Diactoros\ServerRequest))
How to&Answers:

In order to get detail error message of the causes, you need to go to CheckClientCredentials class detail as below

public function handle($request, Closure $next, ...$scopes)
{
    $psr = (new DiactorosFactory)->createRequest($request);

    try {
        $psr = $this->server->validateAuthenticatedRequest($psr);
    } catch (OAuthServerException $e) {
        error_log($e->getHint()); // add this line to know the actual error
        throw new AuthenticationException;
    }

    $this->validateScopes($psr, $scopes);

    return $next($request);
}

Based on the error message. in my question.

The solution is adding this to .htaccess of root folder (not only inside the public folder)

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

There’s also a note in the official documents refer here

Without above configuration, the Authorization header will be ignored during call from anywhere to app. Once ignored, inside class will unable to retrieve this header data

Answer:

In the event you’ve tried everything and nothing seems to work, try clearing your configuration cache. I spent two days reinstalling passport, following a billion tutorials, creating test projects etc. all to eventually realise I needed to clear my cache

php artisan config:cache

Answer:

In case anyone has the same problem, and the selected solution do not solve it. Check the following:

1) Check you are sending the X-CSRF-TOKEN in the header of the request. In my case iḿ using vue with axios:

let token = window.$('meta[name="csrf-token"]').attr('content');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token;

If you are sending it, try changing the following value in vendor/laravel/passport/src/Passport.php line 125 (may change)

From True to False

public static $unserializesCookies = false;

The issue may be similar to the one in https://github.com/laravel/passport/issues/452

An explanation about serialization is in the issue

UPDATE 01/02/2020

As Zac Grierson commented, vendors files should not be modified as they will change in the following

composer update

micksp found a better solution: “add protected static $serialize = false; to your app/Http/Middleware/EncryptCookies.php. Then remove your browser cookies.