在 Laravel 中将 beforeFilter (4.*) 转换为中间件 (5.*)

Converting beforeFilter (4.*) to Middleware (5.*) in Laravel

最近我一直在努力学习使用Laravel。大多数教程都在 4.* 中,但没关系。 Implementing/converting 一些已弃用的功能到目前为止都运行良好。我发现版本 5.* 已弃用 beforeFilter,如:

public function __construct() {
    $this->beforeFilter('csrf', array('on' => ['post', 'put', 'patch', 'delete']));
}

我想将其转换为版本 5.*。据我了解,这可以通过中间件来完成,但我不知道如何才能达到相同的结果。我已经阅读了文档,但这并没有真正帮助我理解这个主题。

app/Http/Middleware 文件夹中已经有一个名为 VerifyCsrfToken.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 = [
        //
    ];
}

任何人都可以指导我进行设置并帮助我更好地理解中间件吗?谢谢。

因为 CSRF 保护是 Laravel 5 附带的东西,这实际上是它在 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken class 中默认检查的东西,您看到 VerifyCsrfToken.php 中正在扩展].

如果您查看如下所示的 handle method of that class, you'll see that the first condition that would make the verification successful, calls the isReading 方法:

/**
 * Determine if the HTTP request uses a ‘read’ verb.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function isReading($request)
{
    return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
}

这与您的 beforeFilter 在 Laravel 4 中所做的等效,因此允许对 "read" 动词执行请求并在使用任何其他动词时自动验证令牌,例如 postputpatchdelete.

如果您查看 Laravel CSRF Protection Documentation,您会看到有一段内容为:

You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken HTTP middleware will verify that the token in the request input matches the token stored in the session.

所以你不再需要那个过滤器了。至于理解中间件在 Laravel 中的工作原理,阅读整个 HTTP Middleware Documentation 将很好地帮助您了解它的工作原理。