Laravel 5: POST without CSRF checking

后端 未结 4 923
醉梦人生
醉梦人生 2021-01-17 19:07

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.

相关标签:
4条回答
  • 2021-01-17 19:16

    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'
    
        ];
    }
    
    0 讨论(0)
  • 2021-01-17 19:30

    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..)

    0 讨论(0)
  • 2021-01-17 19:32

    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...

    0 讨论(0)
  • 2021-01-17 19:35

    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

    0 讨论(0)
提交回复
热议问题