65

I am trying to create a RESTful API by using Laravel. I have created my controller using php artisan make:controller RestController and this is my controller code:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class RestController extends Controller { private $arr = array( array("name"=>"jon", "family"=>"doe"), array("name"=>"jhon", "family" => "doue") ); public function index(){ return json_encode($this->arr); } public function store(Request $request){ return "oops!!"; } public function update (Request $request, $id){ return "test"; } } 

I have added this line of code to create this route in my routes/web.php file:

Route::resource('person', 'RestController'); 

When I try to test this api on GET /person it works fine but on POST and PUT I am getting a 419 status code from Laravel.

4
  • may be validation failes or if its psot request then token not added Commented Sep 17, 2017 at 16:56
  • there is no validation on my controller. what is the token which i must add Commented Sep 17, 2017 at 16:58
  • Have you defined routes for POST request ? Commented Sep 17, 2017 at 17:00
  • no... i use route::resource Commented Sep 17, 2017 at 17:01

8 Answers 8

104

If you are developing REST APIs, its better not add tokens. If you are using 5.4 or 5.5 you can use api.php instead of web.php. In api.php you don't need token verification on post requests.

If you are using web.php, then you can exclude routes that you don't want to validate with CSRF Tokens.

Here is the official documentation:

Excluding URIs From CSRF Protection

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'stripe/*', 'http://example.com/foo/bar', 'http://example.com/foo/*', ]; } 

For reference https://laravel.com/docs/5.5/csrf

Sign up to request clarification or add additional context in comments.

4 Comments

if i want to add token which token i must to use
its not possbile to add laravel token in api .becasue api is consumed from third party app like android or ios or any other web apps
i add Route::resource('person', 'RestController'); to my api.php but still i am getting 419 status code
ya this is becasue of token not there.can you change to protected $except = [ '/*', ]; in App\Http\Middleware\VerifyCsrfToken
37

As per my Knowledge there are two methods to solve this

Method 1: Add CsrF Token

Method 2: Exclude URIs from CSRF protection

How to use

Method 1: Add one more variable to your POST request

_token: "{{ csrf_token() }}" 

Example for Ajax

req = $.ajax({ type: "POST", url: "/search", data: { "key": "value", _token: "{{ csrf_token() }}", }, dataType: "text", success: function(msg) { // ... } }); 

Example if you using forms

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}"> 

Method 2: There is a file named VerifyCsrfToken in following location

yourProjectDirectory/app/Http/Middleware 

Add your URL in following method

 protected $except = [ 'url1/', 'url2/', ]; 

When To use

  • If you are the owner(full control) of API, use Method 1, as CSRF Token adds security to your application.

  • If you are unable to add CSRF Token like in case if you are using any third party API's, webhooks etc., then go for Method 2.

2 Comments

I was having this issue with an ajax request in a javascript game I'm developing. Adding the token solved the issue as I want to keep it.
If you have your javascript in a separate file, it will not be able to access the "{{ csrf_token() }}" for the Ajax call, leading to a 419 status code. To avoid that, add the csrf token to the form. Then reference the form value in your Ajax call: "_token": $('input[name="_token"]').val().
5

For Laravel 11, I did this to disable CSRF token validation (file: /var/www/html/bootstrap/app.php ):

return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // Disable CSRF protection for specific routes <-------------------- Add this $middleware->validateCsrfTokens(except: [ 'api/*', ]); }) ->withExceptions(function (Exceptions $exceptions) { // })->create(); 

Comments

2

I had the same issue when did POST requests to a Laravel API.

I solved the issue sending Accept: application/json in the headers request.

Comments

1

This can solve by excluding csrf protection of specific route you want to.

Inside your middleware folder, edit the file called VerifyCsrfToken.php

protected $except = [ 'http://127.0.0.1:8000/person/' ]; 

Comments

0

Disable statefulApi() 👇, if your SPA runs on a different domain !

->withMiddleware(function (Middleware $middleware): void { // $middleware->statefulApi(); }); 

In Laravel, using $middleware->statefulApi() enables stateful authentication for SPAs that share the same domain as the backend, allowing Laravel Sanctum to use cookies and CSRF protection for secure, session-based requests. However, if your SPA runs on a different domain (e.g., localhost:5000 and localhost:8000), this setup will cause CSRF token mismatch errors, because cookies and CSRF tokens don’t work across domains. In that case, you should remove statefulApi() and use stateless API authentication with Bearer tokens instead.

Comments

-1

I solved this problem by changing my server cache setting. You can disable all of your caching systems (Nginx, Cloudflare, ...) to check it and then turn it on by applying QueryString + Cookie to prevent caching a page with old csrf token in it.

Comments

-1

I was also struggling with getting 419 responses from my backend, but it was actually unrelated to everything that has to do with the specifics of CSRF tokens, server configurations and URI exclusions.

My issue was that I was trying to reach an endpoint in my application like: v1/auth/user/..., but I had let out the prefix api/. So when changing the requested endpoint to api/v1/auth/user, everything worked correctly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.