'Issue with POST requests with Laravel Sanctum and Postman
I have a problem with Sanctum and Postman that's related to this post: SPA Authentication Issues with Sanctum and Postman
I followed everything from the Laravel docs about Sanctum and configured it correctly. Then I followed this tutorial: https://blog.codecourse.com/laravel-sanctum-airlock-with-postman/
Everything is working except for POST requests. When I do login, it works. But then I have a collection without the pre-request Script and when I do a GET request to for example /user
, it will return the logged in user.
But when I change the method to POST
in Laravel and in Postman, I'll get a CSRF token mismatch error.
Does anybody knows what I have to do, to make POST requests working?
Route::middleware('auth:sanctum')->post('/user', function (Request $request) {
return $request->user();
});
Solution 1:[1]
I've been using sanctum
in one of my e-commerce APIs and I've also followed the same tutorial you've linked in the question. It's hard to tell what's the actual problem in your case but it seems like that you're not sending the X-XSRF-TOKEN
header in your POST
requests.
The last paragraph in the above-mentioned tutorial, the writer shows how to hit the /logout
route which is a POST
route.
Solution 2:[2]
Remove this function in the controller
public function __construct()
{
$this->middleware('auth');
}
**Or change it to**
public function __construct()
{
$this->middleware('auth:sanctum');
}
**Also, check your RouteServiceProvider and change your API route to**
Route::prefix('api/v1')
->middleware('auth:sanctum')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Solution 3:[3]
csrf_token is used to validate forms having method POST in laravel and token is created dynamically, two thing you can do
First thing if you are writing api's you need to use https://<base_url>/api
and routes in routes/api.php, there you donot need csrf_token but make sure to use proper api authentication
Second just disable csrf token for those routes until you are testing on postman, once you successfully tested enable again, its provide security
disable like this
<?php namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'submitMyForm/*',
];
}
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 | fhsinchy |
Solution 2 | Mwangi_Muthui |
Solution 3 | Teekay |