在Laravel 5中,如何为特定路由禁用VerifycsrfToken中间件? [英] In Laravel 5, How to disable VerifycsrfToken middleware for specific route?
问题描述
我正在使用Laravel 5开发应用程序.我的应用程序已与VendHQ API连接,我打算通过其Webhook从VendHQ获取一些数据.根据他们的文档
I am using Laravel 5 for developing an app. My app is connected with VendHQ API and I am intended to get some data from VendHQ through their webhook. As per their Documentation
当事件发生并触发网络挂钩时,我们将发送POST 请求到您选择的URL. POST请求将位于 UTF-8字符集和application/x-www-form-urlencoded编码.
When an event happens and triggers a webhook, we’ll send a POST request to a URL of your choosing. The POST request will be in the UTF-8 charset, and application/x-www-form-urlencoded encoding.
问题是,当他们尝试向我的Laravel应用发送POST请求时,没有在他们的发布请求中添加CSRF令牌,并且VerifyCsrfToken
中间件正在寻找令牌,最后它抛出TokenMismatchException
.
The problem is, when they try to send a POST request to my Laravel app, no CSRF Token is added in their post request and VerifyCsrfToken
middleware is looking for a token and finally it throws a TokenMismatchException
.
我的问题是,如何在某些其他路由中避免使用默认的VerifyCsrfToken
中间件,同时保持其他帖子请求处于活动状态?
My question is, how can I avoid this default VerifyCsrfToken
Middleware for some specific routes while keeping other post requests active?
推荐答案
Laravel 5中的所有路由均默认启用CSRF,您可以通过修改app/Http/Middleware/VerifyCsrfToken.php
CSRF is enabled by default on all Routes in Laravel 5, you can disable it for specific routes by modifying 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);
}
这篇关于在Laravel 5中,如何为特定路由禁用VerifycsrfToken中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!