Laravel X-CSRF-Token mismatch with POSTMAN

89.9k views Asked by At

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?

12

There are 12 answers

1
brianlmerritt On BEST ANSWER

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!

1
James Taylor On

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

2
Katsum0to On

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"
0
James Cushing On

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>

1
Cedric On

Adding /api to the url should solve this for most people just testing out their APIs... Eg. https://www.yoursite.com/api/register

3
DEV Tiago França On

Go to app/Http/Middleware/VerifyCsrfToken.php and add this values

    protected $except = [
        '/api/*'
    ];
1
Rohit Bhati On

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.

0
dyedwiper On

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/

0
F KIng On

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,
    ],
0
kachi_dk On

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
0
Kamal___Jangra On

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
0
Tommy Hoang On

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:

  1. Create POSTMAN environment variable named XRSF-TOKEN (or any name you like).

  2. Create a GET method to access <your_host>/sanctum/csrf-cookie

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

  1. At every request, you put into header X-XSRF-TOKEN variable and set value is {{XSRF-TOKEN}} besides other keys.

Done!!!

Every time you receive CSRF missed match message. You re-run request at step 2 to generate new token.

Hope this helps!