Featured image of post Laravel middleware VerifyCsrfToken

Laravel middleware VerifyCsrfToken

從驗證的 原始碼 中可看到,他是如何去驗證動作是否成功。

public function handle($request, Closure $next) {
    if (
        // 如果請求方式是HEAD, GET, OPTIONS通過驗證
        $this->isReading($request) ||
        // 如果是在測試環境中
        $this->runningUnitTests() ||
        // 如果是排除的路由
        $this->inExceptArray($request) ||
        // 如果驗證正確
        $this->tokensMatch($request)
    ) {
        return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

protected function isReading($request) {
    return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
}

protected function runningUnitTests() {
    return $this->app->runningInConsole() && $this->app->runningUnitTests();
}

protected function inExceptArray($request) {
    foreach ($this->except as $except) {
        if ($except !== '/') {
            $except = trim($except, '/');
        }

        if ($request->is($except)) {
           return true;
       }
    }
    return false;
}

protected function tokensMatch($request) {
    $token = $this->getTokenFromRequest($request);

    return is_string($request->session()->token()) &&
           is_string($token) &&
           hash_equals($request->session()->token(), $token);
}

設定token驗證失敗的時候顯示頁面。 app/Exceptions/Handler.php

public function render($request, Exception $exception) {
    if( $exception ){
        return response()
            ->view('errors.401', ['error' => 'Page expired, go back and try again.'], 401);
    }
    return parent::render($request, $exception);
}

設定例外頁面 app/Http/Middleware/VerifyCsrfToken.php

參考資料:

Licensed under CC BY-NC-SA 4.0