4

I am new in laravel. I want to create REST API's with Laravel, I have used Dingo for it. Now my problem is when I am sending post request

CSRF token mismatch is error is throwing

and for web version we have used CSRF token for validating the request..

can anyone help me for solving CSRF token mismatch error in laravel 5.1.

Thanks in advance...

3
  • did you add the csrf_token() ? Jan 27, 2016 at 9:52
  • 2
    if you want you can exclude specific url from CSRF verification. Jan 27, 2016 at 10:32
  • Add the excluded URLs in this file.
    – Shubhamoy
    Apr 5, 2016 at 6:08

4 Answers 4

8

In your app\http\Middleware\VerifyCsrfToken.php file.

edit $except property with:

protected $except = [
  'yourapi/*' 
];

This will exclude your api routes from CSRF verification.And keep it up for other things like your frontend.

5

Don't use CSRF tokens in an API. You should remove the middleware from app/Http/Kernel.php (on line 20) and use a different authentication method for your API.

3
  • Thanks for your help. I have removed CSRF token and used jWT for token authentication
    – Vikas Kad
    Jan 28, 2016 at 7:06
  • This is not the only answer to this question. RESTful API's should be stateless is the general argument, but being stateless is not always more important than being secure. This article is worth a read stormpath.com/blog/…
    – Tim Ogilvy
    Oct 15, 2018 at 1:37
  • Also "Don't use CSRF tokens in an API" could use a reference.
    – Tim Ogilvy
    Oct 15, 2018 at 1:38
1

This is somewhat related. So I am adding it for anyone else who comes across this page. PostMan requests can also return the same issue. But you cannot implement the CSRF token the same way as you can on AJAX or within HTML and laravel side of the code. So here is a solution for PostMan requests.

Postman - "CSRF Token Mismatch" | Laravel REST API Tutorial
YOUTUBE : https://youtu.be/EgBq4IVnfnA

A useful article to support the video
https://community.postman.com/t/get-body-variables-from-pre-request-script/8666

-1

You probably just aren't passing a CSRF-token in your API request to Laravel, causing the exception.

2
  • do you know how can I get CSRF token because I am using postman for sending post request
    – Vikas Kad
    Jan 27, 2016 at 9:49
  • You could add a route that returns a CSRF token for you, but you should look into csrf exclusion for API routes.
    – jbehrens94
    Jan 27, 2016 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.