删除特定路由的 Csrf 验证


Remove Csrf verifcation of specific route

我正在尝试使用我的 laravel 应用程序创建一个 api,但是当我对路由发出发布请求时,Laravel默认尝试验证 csrf 令牌。因此,我想删除 api 路由的此验证。我想维护前端请求的验证。但是当我在app/Http/Middleware/VerifyCsrfToken.php中添加异常路由时,我收到此错误:

block_exception clear_fix

这是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 并添加要排除的 URL。

<?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',
];

根据Laravel文档:

"包含在 Web 中间件组中的 VerifyCsrfToken 中间件将自动验证请求输入中的令牌是否与存储在会话中的令牌匹配。"

因此,如果您从该特定路由中删除"Web中间件",您应该很好。

https://laravel.com/docs/5.2/routing#csrf-protection

换句话说,不要将您的路由放在路由中的 Web 中间件组下.php

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');

根据我的朋友Charles的要求,你也可以把你的路由放在VerifyCrsfToken中间件$except数组中。

<?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 = [
        'your_custom_route/*',
    ];
}