我尝试使用我的laravel应用程序创建api,但是当我对路径发出post请求时,Laravel默认尝试验证csrf令牌。所以,我想删除api路由的验证。我想维护前端请求的验证。但是当我在app / Http / Middleware / VerifyCsrfToken.php中添加异常路由时,我收到此错误:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
'log_bounces_complaints',
];
}
这是VerifyCsrfToken.php
<?php if (the_field( 'attribute_1' ) & the_field( 'value_1' ) != "") { ?>
<li style="line-height:2.25em;border-top:1px solid #dcdcdc;"><p style="font-size:15px;margin-bottom:0;"><?php the_field( 'attribute_1' ); ?> <span style="float:right;font-weight:600;font-family:'Varela Round';"><?php the_field( 'value_1' ); ?></span></p></li>
<?php } ?>
答案 0 :(得分:4)
只需扩展VerifyCsrfToken并添加要排除的网址即可。
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {
protected $except_urls = [
'your_specific_url/new_url',
'your_specific_url/new_url_2',
...
];
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',
];
答案 1 :(得分:3)
根据Laravel文件:
&#34;包含在Web中间件组中的VerifyCsrfToken中间件将自动验证请求输入中的令牌是否与会话中存储的令牌匹配。&#34;
因此,如果您删除&#34;网络中间件&#34;从那条特定的路线你应该是好的。
https://laravel.com/docs/5.2/routing#csrf-protection
换句话说,不要将您的路由放在routes.php中的Web中间件组下
Route::group(['middleware' => 'web'], function () {
// all your routes will go through CSRF check
}
// Anything outside will not go through the CRSF check unless you
// define a middleware when constructing your controller.
Route::post('ajax', 'YourController@yourFunction');