Laravel Sanctum unauthenticated using postman

Viewed 3621

I follow the Laravel official document step by step.

When I send a request to {{host}}/api/login, I can receive the response that includes token. EVerything is correct.

But when I try to send a request to {{host}}/api/user, it is always unauthenticated.

I checked my code several times, I cannot fix it.

In my .env file, I set as following, my backend host is http://laravel_8_api.test

SESSION_DOMAIN=.laravel_8_api.test SANCTUM_STATEFUL_DOMAINS=.laravel_8_api.test

How can I make it work? Please help me. The postman request screenshot

The code is in this link "https://github.com/ramseyjiang/laravel_8_api"

3 Answers

Try this if you haven't

The reason this isn't working is that Sanctum is denying the authenticated request based on the referrer.

Add Referer to the request header in postman.

enter image description here

//api.php

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

middleware should be auth:sanctum instead of auth:api

In the official document, it forgets to modify the config/auth.php

'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
            'hash' => false,
        ],

After that, it will fix this issue.

Don't need to modify code in the code in the api.php I mean it doesn't need to change auth:sanctum to the auth:api, if change it, it will make another issue as the link Laravel Sanctum : column not found: 1054 Unknown column 'api_token' in 'where clause'

Related