You are here

public function UserLoginHttpTest::testLogoutCsrfProtection in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/tests/src/Functional/UserLoginHttpTest.php \Drupal\Tests\user\Functional\UserLoginHttpTest::testLogoutCsrfProtection()

Tests csrf protection of User Logout route.

File

core/modules/user/tests/src/Functional/UserLoginHttpTest.php, line 457

Class

UserLoginHttpTest
Tests login and password reset via direct HTTP.

Namespace

Drupal\Tests\user\Functional

Code

public function testLogoutCsrfProtection() {
  $client = \Drupal::httpClient();
  $login_status_url = $this
    ->getLoginStatusUrlString();
  $account = $this
    ->drupalCreateUser();
  $name = $account
    ->getAccountName();
  $pass = $account->passRaw;
  $response = $this
    ->loginRequest($name, $pass);
  $this
    ->assertEquals(200, $response
    ->getStatusCode());
  $result_data = $this->serializer
    ->decode($response
    ->getBody(), 'json');
  $logout_token = $result_data['logout_token'];

  // Test third party site posting to current site with logout request.
  // This should not logout the current user because it lacks the CSRF
  // token.
  $response = $this
    ->logoutRequest('json');
  $this
    ->assertEquals(403, $response
    ->getStatusCode());

  // Ensure still logged in.
  $response = $client
    ->get($login_status_url, [
    'cookies' => $this->cookies,
  ]);
  $this
    ->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);

  // Try with an incorrect token.
  $response = $this
    ->logoutRequest('json', 'not-the-correct-token');
  $this
    ->assertEquals(403, $response
    ->getStatusCode());

  // Ensure still logged in.
  $response = $client
    ->get($login_status_url, [
    'cookies' => $this->cookies,
  ]);
  $this
    ->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);

  // Try a logout request with correct token.
  $response = $this
    ->logoutRequest('json', $logout_token);
  $this
    ->assertEquals(204, $response
    ->getStatusCode());

  // Ensure actually logged out.
  $response = $client
    ->get($login_status_url, [
    'cookies' => $this->cookies,
  ]);
  $this
    ->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);
}