Reputation: 3255
I try to talk to my REST API built with Laravel. But the call with POSTMAN is rejected due to a token mismatch. I guess I need to include the CSRF token in the header. But do I need the encrypted one? When I insert this token I still get the error that there is a token mismatch.
I retrieve my token by using:
$encrypter = app('Illuminate\Encryption\Encrypter');
$encrypted_token = $encrypter->encrypt(csrf_token());
return $encrypted_token;
but is this supposed to change on every refresh?
Upvotes: 33
Views: 102977
Reputation: 3002
inside bootstrap/app.php
, in the withMiddleware()
:
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
'stripe/*',
'http://localhost:8000/YOUR_POST_ENDPOINT'
]);
})
Upvotes: 0
Reputation: 11
Instead of defining your Route
in routes/web.php
define your Route
in routes/api.php
Route::post('/user_api', [UserController::class, 'store']);
And the hit a api request in POSTMAN like this.
http://localhost:8000/api/user_api
Upvotes: 0
Reputation: 355
My solution is not so convenient but work for Laravel 8,9,10 as I've tested. You don't need to change initial values of Laravel as well:
Create POSTMAN environment variable named XRSF-TOKEN (or any name you like).
Create a GET method to access <your_host>/sanctum/csrf-cookie
In the Tests section (POSTMAN), you input this snippet of code:
pm.environment.set("XSRF-TOKEN", pm.cookies.get("XSRF-TOKEN"));
This will set the generated token from back-end into Postman Environment variable XSRF-TOKEN.
Done!!!
Every time you receive CSRF missed match
message. You re-run request at step 2 to generate new token.
Hope this helps!
Upvotes: 2
Reputation: 413
For anyone visiting this recently
Vendor packages also use the .env
(SESSION_DOMAIN
and SANCTUM_STATEFUL_DOMAINS
), so sometimes there is weird behavior.
Remove these from the .env
if present
# SESSION_DOMAIN=
# SANCTUM_STATEFUL_DOMAINS=
Add these to the .env
. Make sure the URL is in full (scheme, domain and port (when in development))
APP_URL=http://localhost:8000
FRONTEND_URLS=http://localhost:5173,http://localhost:5174,http://localhost:5175,http://localhost:5176
Add these to config/cors.php
return [
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => explode(',', env('FRONTEND_URLS')),
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
]
Add these to config/sanctum.php
return [
...
'stateful' => explode(
',',
env(
'SANCTUM_STATEFUL_DOMAINS',
sprintf(
'%s%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : '',
env('FRONTEND_URLS')
? implode(
',',
array_map(function ($url) {
return parse_url($url, PHP_URL_HOST);
}, explode(',', env('FRONTEND_URLS')))
)
: ''
)
)
),
...
]
Make sure this line is present in kernel.php
protected $middlewareGroups = [
'web' => [
...
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // <---
...
],
];
Then don't forget to clear the cache both in development and server.
php artisan config:clear
php artisan route:clear
php artisan cache:clear
Upvotes: 1
Reputation: 498
I was following this tutorial when I encountered the error.I was making requests to routes in my web.php and while get requests were successful post requests returned the Token mismatch error even after adding an X-XSRF-TOKEN header. I came across this post that recommended commenting out \App\Http\Middleware\VerifyCsrfToken::class line in your web middleware group in app\Http\kernel.php file when making post requests to routes defined in your web.php. This worked for me. Just do not forget to uncomment it after you are done testing.
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
],
Upvotes: 2
Reputation: 338
I just had the same issue and this answer finally helped me solving it: https://stackoverflow.com/a/67435592/11854580
Apparently the CSRF token needs to be updated on every POST request. (Not on every GET request somehow.) You can solve this with a pre-request-script in Postman as explained in this tutorial: https://blog.codecourse.com/laravel-sanctum-airlock-with-postman/
Upvotes: 1
Reputation: 496
If you are making REST API
use api.php
for writing routes, not web.php
, according to Laravel documentation web.php
is for writing routes for the website that's why you see csrf-token error while using it like API, So for API we have the api.php
file which will not give you a csrf-token error.
Upvotes: 5
Reputation: 1696
Go to app/Http/Middleware/VerifyCsrfToken.php
and add this values
protected $except = [
'/api/*'
];
Upvotes: 18
Reputation: 43
Adding /api to the url should solve this for most people just testing out their APIs... Eg. https://www.yoursite.com/api/register
Upvotes: -4
Reputation: 728
I had this error while using a baseURL
variable in my Postman environment. Turns out I was calling the site's URL without /api
at the end. Sounds silly, but just to eliminate user error make sure you check that your request URL is based on:
✅ https://<your-site-url>/api
Not:
❌ https://<your-site-url>
Upvotes: 7
Reputation: 2852
If you aren't using forms - for an API for example - you can follow the steps here https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0:
Essentially, add the following to your blade or twig header
<meta name="csrf-token" content="{{ csrf_token() }}">
Install Postman Interceptor if not already installed, and turn it on
Then, in your browser log into the site (you need to be authorised), and either inspect element or view source to retrieve the token
In Postman, set GET/POST etc as needed, and in your header create a new pair
X-CSRF-TOKEN tokenvaluetobeinserted235kwgeiOIulgsk
Some people recommend turning off the CSRF token when testing the API, but then you aren't really testing it are you.
If you do find you still have errors, check the response back using preview
as Laravel tends to be fairly explicit with their error messages. If nothing is coming back, check your php_error.log
(what ever it is called).
ps Oct 2018 - I now user Laravel Passport for handling API registration, logins and user tokens - worth a look!
Upvotes: 30
Reputation: 89
Use Postman
Make a GET request to any page that has
<meta name="csrf-token" content="{{ csrf_token() }}">
Copy the value from the response.
Add a header field to your POST request:
"X-CSRF-TOKEN: "copied_token_in_previous_get_response"
Upvotes: 6
Reputation: 261
Yes it changes every refresh. You should be putting it in the view and when you post it needs to be sent as the value of the "_token" POST var.
If you are just using a standard POST just add this to the form:
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
If you are using AJAX make sure you grab the value of _token and pass it with the request.
REF: http://laravel.com/docs/5.1/routing#csrf-protection
Upvotes: 6