简体   繁体   中英

How to disable csrf token for some url in Laravel 4

The question is in the title : How to disable CSRF Token only for some url in Laravel 4 ?

I know in Laravel 5 it's easy with the variable $except in the middleware but in Laravel 4 I don't find the solution...

One way is to extend the VerifyCsrfToken and have an array of no csrf urls inside :

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {

    protected $except_urls = [
        'contact/create',
        'contact/update',
        ...
    ];

    public function handle($request, Closure $next)
    {
        $regex = '#' . implode('|', $this->except_urls) . '#';

        if ($this->isReading($request) || $this->tokensMatch($request) || preg_match($regex, $request->path()))
        {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

}

And change in Kernel to point the new middleware :

protected $middleware = [

    ...

    'App\Http\Middleware\VerifyCsrfToken',
];

You can find more details at there:

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

Laravel 5: POST whithout CSRF checking

You can do this by modifying VerifyCrsfToken.php class and by providing $openRoutes and yes you will be playing with fire when touching base classes. :)

//app/Http/Middleware/VerifyCsrfToken.php

//add an array of Routes to skip CSRF check
private $openRoutes = ['free/route', 'free/too'];

//modify this function
public function handle($request, Closure $next)
    {
        //add this condition 
    foreach($this->openRoutes as $route) {

      if ($request->is($route)) {
        return $next($request);
      }
    }

    return parent::handle($request, $next);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM