basicAuthGet example

    $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.');

    

  public function testBasicAuth() {
    // Enable page caching.     $config = $this->config('system.performance');
    $config->set('cache.page.max_age', 300);
    $config->save();

    $account = $this->drupalCreateUser();
    $url = Url::fromRoute('router_test.11');

    // Ensure we can log in with valid authentication details.     $this->basicAuthGet($url$account->getAccountName()$account->pass_raw);
    $this->assertSession()->pageTextContains($account->getAccountName());
    $this->assertSession()->statusCodeEquals(200);
    $this->mink->resetSessions();
    $this->assertSession()->responseHeaderDoesNotExist('X-Drupal-Cache');
    // Check that Cache-Control is not set to public.     $this->assertSession()->responseHeaderNotContains('Cache-Control', 'public');

    // Ensure that invalid authentication details give access denied.     $this->basicAuthGet($url$account->getAccountName()$this->randomMachineName());
    $this->assertSession()->pageTextNotContains($account->getAccountName());
    $this->assertSession()->statusCodeEquals(403);
    
Home | Imprint | This part of the site doesn't use cookies.