12

It seems that Laravel 5 by default applies the CSRF filter to all non-get requests. This is OK for a form POST, but might be a problem to an API that POSTs DELETEs etc.

Simple Question:

How can I set a POST route with no CSRF protection?

Ersoy
  • 8,816
  • 6
  • 34
  • 48
igaster
  • 12,983
  • 6
  • 26
  • 27
  • 1
    That means the protection is removed. Better pass the token as part of the API calls. (I know this it's an old question, just warning new visitors) – Kwebble Jun 14 '17 at 15:16

4 Answers4

21

Go to app/Http/Middleware/VerifyCsrfToken.php and then enter your routes(for which you want to disable csrf token) in the $except array.

for example:

class VerifyCsrfToken extends BaseVerifier
{

    protected $except = [

        '/register'

    ];
}
Luboš Turek
  • 6,273
  • 9
  • 40
  • 50
Shreya Maria
  • 488
  • 8
  • 18
12

You can exclude URIs from CSRF by simply adding them to the $except property of the VerifyCsrfToken middleware (app/Http/Middleware/VerifyCsrfToken.php):

<?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 = [
        'api/*',
    ];
}

Documentation: http://laravel.com/docs/5.1/routing#csrf-protection

mshakeel
  • 604
  • 6
  • 21
2

My hack to the problem:

CSRF is now a "middleware" registered globally in App\Http\Kernel.php. Removing it will default to no CSRF protection (Laravel4 behavior).

To enable it in a route:

  1. Create a short-hand key in your app/Providers/RouteServiceProvider.php :

    protected $middleware = [
      // ....
      'csrf'  => 'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
    ];
    
  2. You can now enable it to any Route:

    $router->post('url', ['middleware' => 'csrf', function() {
     ... 
    }]);
    

Not the most elegant solution IMO...

igaster
  • 12,983
  • 6
  • 26
  • 27
0

just listen to this. Just before 30 minute i was facing this same problem. Now it solved. just try this.

Goto App -> HTTP-> Kernel

open the kernel file.

there you can see : \App\Http\Middleware\VerifyCsrfToken::class,

just disable this particular code using //

Thatz it! This will work!

So that you can remove the middleware from the API calling (if you want so..)

Sunil
  • 95
  • 3
  • 1
    This is a very bad solution. You are now [vulnerable to CSRF attacks](https://owasp.org/www-community/attacks/csrf) – Binar Web Feb 04 '21 at 14:39