将中间件附加到所有方法

Attach middleware to all method

我在 Laravel 4.2 Route::when('*', 'csrf', ['post']); 中有这个,向所有 post 插入 csrf 验证,我如何移植到 Larevel 5.2?

这是我自己的csrf,没有使用默认提供的Laravel:

<?php
namespace App\Http\Middleware;
use Closure;
use Input;
class VerifyCsrfToken1
{
    public function handle($request, Closure $next)
    {
        $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
        if ($request->session()->token() === $token) {
            return $next($request);
        }
        throw new TokenMismatchException;
    }
}

我创建了我的个人 csrf 中间件,但我不知道如何将它们附加到所有 post 请求

我想通过 Route 的外观将它附加到所有 post。 (文件routes.php)

谢谢:)

Laravel 5 连接中间件的方式有点不同,您不会通过 Request 外观来执行此操作。

您想首先将您的中间件注册为全局的。打开 app/Http/Kernel.php 并将其添加到全局 $middleware 数组。

protected $middleware = [
    VerifyCsrfToken1::class
    ...

然后在您的中间件 class 中,检查它是否正在处理 POST 请求。如果没有,让它直接传递请求而不做任何事情。

if($request->method() != "POST") {
    // Move right along
    return $next($request);
}

旁注:如您所述,Laravel 已经内置了 VerifyCsrfToken 中间件。如果可能的话,我建议尝试对此进行调整。