Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel X-CSRF-Token mismatch with POSTMAN

Tags:

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?

like image 460
sesc360 Avatar asked Jun 10 '15 12:06

sesc360


1 Answers

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!

like image 97
brianlmerritt Avatar answered Sep 20 '22 14:09

brianlmerritt