如何检查后端的 csrf 令牌是否不匹配?

How to check if csrf token is mismatch in back end?

Laravel 5.3^ 有没有办法检查令牌是否不匹配

例如这样的事情:

if (csrf_token mismatch) {
    return redirect()->back();
}

这是在自动包含在 web 中间件组中的默认中间件 VerifyCsrfToken 中完成的。有关它的更多信息,请参见 CSRF protection documentation.

如果您想使用特定的错误消息重定向回来,请在位于 app/Exceptions/Handler.php 的渲染函数中放置以下内容:

if ($e instanceof \Illuminate\Session\TokenMismatchException)
{
    return back()
        ->with('message', 'Your message here.');
}

你可以用这个,

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

    if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
        return redirect()->back();
        }

在您的 Kernel.php 中,您的中间件组已定义。在那里添加验证 CSRF 令牌例程。请参阅以下示例...

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

然后在你的 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 = [
        //
    ];
}

您也可以通过在 protected $except 数组中指定路径来创建例外。

CSRF 令牌验证

protected function tokensMatch($request)
{
    $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

    return $request->session()->token() == $token;
}