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

Ari*_*que 25 php csrf-protection laravel laravel-5

我正在使用Laravel 5开发应用程序.我的应用程序与VendHQ API相关联,我打算通过他们的webhook从VendHQ获取一些数据.根据他们的文档

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

问题是,当他们尝试向我的Laravel应用程序发送POST请求时,他们的帖子请求中没有添加CSRF令牌,VerifyCsrfToken中间件正在寻找令牌,最后它会抛出一个TokenMismatchException.

我的问题是,如何VerifyCsrfToken在保持其他帖子请求有效的同时避免某些特定路由的默认中间件?

小智 53

在Laravel 5中,这已经有点懊恼了.现在,您只需$except在类的数组中添加要从csrftoken验证中排除的路由

'VerifyCsrfToken'(\ app\Http\Middleware\VerifyCsrfToken.php):

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        // Place your URIs here
    ];
}
Run Code Online (Sandbox Code Playgroud)

例子:

1.如果您使用路线组:

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

您的$except数组看起来像:

protected $except = ['api/v2/users/valid'];
Run Code Online (Sandbox Code Playgroud)

2.如果您使用简单的路线

Route::post('users/valid','UsersController@valid');
Run Code Online (Sandbox Code Playgroud)

您的$except数组看起来像:

protected $except = ['users/valid'];
Run Code Online (Sandbox Code Playgroud)

3.如果要排除主路径下的所有路由(本例中为用户)

您的$except数组看起来像:

protected $except = ['users/*'];
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*dis 18

默认情况下,在Laravel 5中的所有路由上启用CSRF,您可以通过修改app/Http/Middleware/VerifyCsrfToken.php来禁用特定路由

//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);
  }
Run Code Online (Sandbox Code Playgroud)

资源

  • 其他答案中所示的使用“ protected $ except = ['/ specificroutes *'];”的方法更简单 (3认同)

小智 8

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

protected $except = [
'users/get_some_info',
];
Run Code Online (Sandbox Code Playgroud)

用户部分将是您的控制器,"get_some_info"将是操作.执行此更改后,请确保在routes.php中添加路由.


小智 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'
];
Run Code Online (Sandbox Code Playgroud)