function SessionAuthenticationTest::testSessionFromBasicAuthenticationDoesNotLeak

Same name in other branches
  1. 9 core/modules/system/tests/src/Functional/Session/SessionAuthenticationTest.php \Drupal\Tests\system\Functional\Session\SessionAuthenticationTest::testSessionFromBasicAuthenticationDoesNotLeak()
  2. 8.9.x core/modules/system/tests/src/Functional/Session/SessionAuthenticationTest.php \Drupal\Tests\system\Functional\Session\SessionAuthenticationTest::testSessionFromBasicAuthenticationDoesNotLeak()
  3. 10 core/modules/system/tests/src/Functional/Session/SessionAuthenticationTest.php \Drupal\Tests\system\Functional\Session\SessionAuthenticationTest::testSessionFromBasicAuthenticationDoesNotLeak()

Check that a basic authentication session does not leak.

Regression test for a bug that caused a session initiated by basic authentication to persist over subsequent unauthorized requests.

File

core/modules/system/tests/src/Functional/Session/SessionAuthenticationTest.php, line 53

Class

SessionAuthenticationTest
Tests if sessions are correctly handled when a user authenticates.

Namespace

Drupal\Tests\system\Functional\Session

Code

public function testSessionFromBasicAuthenticationDoesNotLeak() : void {
    // This route is authorized through basic_auth only, not cookie.
    $protected_url = Url::fromRoute('session_test.get_session_basic_auth');
    // This route is not protected.
    $unprotected_url = Url::fromRoute('session_test.get_session_no_auth');
    // Test that the route is not accessible as an anonymous user.
    $this->drupalGet($protected_url);
    $session = $this->getSession();
    $this->assertSession()
        ->statusCodeEquals(401);
    // We should be able to access the route with basic authentication.
    $this->basicAuthGet($protected_url, $this->user
        ->getAccountName(), $this->user->passRaw);
    $this->assertSession()
        ->statusCodeEquals(200);
    // Check that the correct user is logged in.
    $this->assertEquals($this->user
        ->id(), json_decode($session->getPage()
        ->getContent())->user, 'The correct user is authenticated on a route with basic authentication.');
    $session->restart();
    // If we now try to access a page without basic authentication then we
    // should no longer be logged in.
    $this->drupalGet($unprotected_url);
    $this->assertSession()
        ->statusCodeEquals(200);
    $this->assertEquals(0, json_decode($session->getPage()
        ->getContent())->user, 'The user is no longer authenticated after visiting a page without basic authentication.');
    // If we access the protected page again without basic authentication we
    // should get 401 Unauthorized.
    $this->drupalGet($protected_url);
    $this->assertSession()
        ->statusCodeEquals(401);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.