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

时间:2017-03-28 19:16:22

标签: laravel csrf

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

例如:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="button-1" class="btn"></button>
<button id="button-2" class="btn"></button>
<button id="button-3"  class="btn"></button>
<div id="thebarofpower"></div>

3 个答案:

答案 0 :(得分:1)

在您的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;
}

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

你可以使用它,

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

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