'Laravel Sanctum unauthenticated using postman
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"
Solution 1:[1]
//api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
middleware should be auth:sanctum
instead of auth:api
Solution 2:[2]
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.
Solution 3:[3]
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'
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 | Majharul Nayem |
Solution 2 | Joseph Ajibodu |
Solution 3 | Ramsey Jiang |