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 d
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>
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!
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"
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