You are here

public function CsrfRequestHeaderAccessCheck::access in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Access/CsrfRequestHeaderAccessCheck.php \Drupal\Core\Access\CsrfRequestHeaderAccessCheck::access()

Checks access.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request object.

\Drupal\Core\Session\AccountInterface $account: The currently logged in account.

Return value

\Drupal\Core\Access\AccessResultInterface The access result.

File

core/lib/Drupal/Core/Access/CsrfRequestHeaderAccessCheck.php, line 92

Class

CsrfRequestHeaderAccessCheck
Access protection against CSRF attacks.

Namespace

Drupal\Core\Access

Code

public function access(Request $request, AccountInterface $account) {
  $method = $request
    ->getMethod();

  // Read-only operations are always allowed.
  if (in_array($method, [
    'GET',
    'HEAD',
    'OPTIONS',
    'TRACE',
  ], TRUE)) {
    return AccessResult::allowed();
  }

  // This check only applies if
  // 1. the user was successfully authenticated and
  // 2. the request comes with a session cookie.
  if ($account
    ->isAuthenticated() && $this->sessionConfiguration
    ->hasSession($request)) {
    if (!$request->headers
      ->has('X-CSRF-Token')) {
      return AccessResult::forbidden()
        ->setReason('X-CSRF-Token request header is missing')
        ->setCacheMaxAge(0);
    }
    $csrf_token = $request->headers
      ->get('X-CSRF-Token');

    // @todo Remove validate call using 'rest' in 8.3.
    //   Kept here for sessions active during update.
    if (!$this->csrfToken
      ->validate($csrf_token, self::TOKEN_KEY) && !$this->csrfToken
      ->validate($csrf_token, 'rest')) {
      return AccessResult::forbidden()
        ->setReason('X-CSRF-Token request header is invalid')
        ->setCacheMaxAge(0);
    }
  }

  // Let other access checkers decide if the request is legit.
  return AccessResult::allowed()
    ->setCacheMaxAge(0);
}