在Laravel 5中,如何针对特定路由禁用VerifycsrfToken中间件?

33
我正在使用 Laravel 5 开发应用程序。我的应用程序与 VendHQ API 相连,并且我打算通过他们的 webhook 获取一些数据。根据他们的文档
  

当事件触发 Webhook 并发送 POST 请求到您选择的 URL 时,我们将向其发送。POST 请求将采用 UTF-8 字符集和 application/x-www-form-urlencoded 编码。

问题在于,当他们尝试向我的 Laravel 应用程序发送 POST 请求时,没有在他们的 POST 请求中添加 CSRF Token,而 VerifyCsrfToken 中间件正在寻找令牌,最终会抛出一个 TokenMismatchException
我的问题是,如何在保持其他 POST 请求活动的同时避免这个默认的 VerifyCsrfToken 中间件对某些特定路由进行操作?

你使用的是Laravel 5还是5.1? - Alex Kyriakidis
@Alexandros 这是 Laravel 5。 - Ariful Haque
4个回答

70
在Laravel 5中,这方面已经发生了一些变化。现在,您可以在类的$except数组中添加要从csrftoken验证中排除的路由。
class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        // Place your URIs here
    ];
}

示例:

1. 如果你正在使用路由组:

Route::group(array('prefix' => 'api/v2'), function()
{
    Route::post('users/valid','UsersController@valid');
});

您的$except数组看起来像:

protected $except = ['api/v2/users/valid'];

2. 如果您正在使用简单路由

Route::post('users/valid','UsersController@valid');

您的$except数组看起来像:

protected $except = ['users/valid'];

3. 如果您想要排除主路由下的所有路由(在此示例中为用户),

您的$except数组应如下所示:

protected $except = ['users/*'];

请参考:http://laravel.com/docs/master/routing#csrf-excluding-uris


非常有用的知识 - Anoop P S
Route::middleware('isUser')->group(function () { });那么我如何在这种情况下绕过令牌呢? - kaann.gunerr

22

Laravel 5中默认启用了所有路由的CSRF保护,您可以通过修改app / Http / Middleware / VerifyCsrfToken.php文件来禁用特定路由的CSRF保护。

//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);
  }


7
其他回答中展示的使用protected $except = ['/specificroutes*'];的方法更为简单。 - PaulH
@PaulH,这在laravel 5.0上不起作用。 - meti

13

如果您使用的是5.2版,则在app/Http/Middleware/VerifyCsrfToken.php中,您可以将路由添加到属性:protected $except

例如:

protected $except = [
    'users/get_some_info',
];

在进行此更改后,请确保将路由添加到您的routes.php文件中。


您还可以使用通配符,例如 '*users/get_some_info*' - Mtxz

5
将您的路由添加到App\Http\Middleware\VerifyCsrfToken.php文件中:
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'route-name-1', 'route-name-2'
];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接