【发布时间】:2017-07-20 21:51:01
【问题描述】:
问题在标题中:How to disable CSRF Token only for some url in Laravel 4?
我知道在 Laravel 5 中使用中间件中的变量 $except 很容易,但在 Laravel 4 中我找不到解决方案...
【问题讨论】:
问题在标题中:How to disable CSRF Token only for some url in Laravel 4?
我知道在 Laravel 5 中使用中间件中的变量 $except 很容易,但在 Laravel 4 中我找不到解决方案...
【问题讨论】:
一种方法是扩展 VerifyCsrfToken 并在其中包含一个没有 csrf url 的数组:
<?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;
}
}
并更改内核以指向新的中间件:
protected $middleware = [
...
'App\Http\Middleware\VerifyCsrfToken',
];
您可以在此处找到更多详细信息:
【讨论】:
您可以通过修改 VerifyCrsfToken.php 类并提供 $openRoutes 来做到这一点,是的,您在接触基类时会玩火。 :)
//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);
}
【讨论】: