Kasnady
Kasnady

Reputation: 2279

Always got "message": "Unauthenticated." - Laravel Passport

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))

Upvotes: 14

Views: 67616

Answers (10)

Jnanaranjan
Jnanaranjan

Reputation: 1322

In Laravel 10

Make sure you have the set up the SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS set correctly.

Upvotes: 0

Bình Duy
Bình Duy

Reputation: 1

I try (routes/api.php)

auth:api

instead of

auth:sanctum

It worked for me. I think cause using wrong guard.

Upvotes: 0

Anupam Verma
Anupam Verma

Reputation: 69

In case anyone has the same problem, and the selected solution do solve it. Check the following: if you go alway respose{ "message": "Unauthenticated." } The solution is adding this to .htaccess of root folder (not only inside the public folder)

Options -MultiViews -Indexes
RewriteEngine On

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

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Upvotes: 1

Simeon Anunciado
Simeon Anunciado

Reputation: 1

For those getting error message Unauthenticated even if the token is correct, just replace laravel 8 prebuilt routes api:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

into

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Upvotes: 0

LAMLAM
LAMLAM

Reputation: 1

I had same problem with Laravel 8 + Postman and I was encrypt password in Database to Bcypt (default laravel encrypt for password of Users model). I was resolve the problem.

image 1 image 2

Upvotes: 0

Jijesh Cherayi
Jijesh Cherayi

Reputation: 1125

In Ubuntu, do the following.

Enable the rewrite mode.

sudo a2enmod rewrite

Go to cd /etc/apache2

Then open apache2.conf nano apache2.conf and find out the following line and change AllowOverride None to AllowOverride All as shown below.

# /etc/apache2/apache2.conf
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Finally, restart apache2 server

sudo service apache2 restart

Upvotes: 3

Garnara Vishal
Garnara Vishal

Reputation: 26

Paste below code in .htaccess file in your project root folder.

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1

Upvotes: 0

Savlon
Savlon

Reputation: 779

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

Upvotes: 11

Emitate
Emitate

Reputation: 7

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."

Upvotes: -2

Kasnady
Kasnady

Reputation: 2279

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

Upvotes: 33

Related Questions