Tuesday, May 13, 2025

Handling HTTP popup authentication in Playwright

 In this example we will explore how to handle http authentication popup in playwright with simple example. Handling HTTP popup authentication in Playwright involves managing scenarios where a webpage triggers a browser-level authentication dialog (e.g., HTTP Basic Authentication). Playwright provides several ways to handle this. Below is a detailed explanation of how to handle HTTP popup authentication in Playwright, including code examples, best practices, and considerations.

Handling HTTP popup authentication in Playwright


Handle authentication popup by setting credentials

In this example Playwright allows you to provide HTTP authentication credentials when creating a browser context, bypassing the authentication dialog entirely. This is done using the httpCredentials option in browser.newContext().

// @ts-check
import { test, expect } from '@playwright/test';

test('Authentication popup handle example 1', async ({browser}) => {

  const context = await browser.newContext({
    httpCredentials: {
      username: 'admin',
      password: 'admin'
    }
  });

  const page = await context.newPage();
  await page.goto('https://practice.expandtesting.com/basic-auth'); // the site requiring HTTP auth
  await expect(page.locator("//b[contains(text(),'Congratulations! You must have the proper credentials.')]")).toBeVisible();

  // Do other actions...
  await browser.close(); 
  
});

Handle authentication popup using setExtraHTTPHeaders

In this example we are going to use setExtraHTTPHeaders. you can use setExtraHTTPHeaders() to add custom headers like Authorization to every request from a page or context — but this does not replace httpCredentials when dealing with true browser-level HTTP Basic Authentication popups (401 challenge responses).

// @ts-check
import { test, expect } from '@playwright/test';

test('Authentication popup handle using  basic authentication', async ({browser}) => {

  const context = await browser.newContext();
  const page = await context.newPage();
  
  const username = "admin";
  const password = "admin";
  const authHeader = 'Basic '+ btoa(username+':'+password);
  page.setExtraHTTPHeaders({Authorization : authHeader });
  await page.goto('https://practice.expandtesting.com/basic-auth'); // the site requiring HTTP auth
  await expect(page.locator("//b[contains(text(),'Congratulations! You must have the proper credentials.')]")).toBeVisible();

  // Do other actions...
  await browser.close(); 
  
});

This is all about handling http authentication popup handling in playwright. Use httpCredentials for Efficiency: Prefer pre-authentication for most automation scenarios to avoid dialog handling.


No comments:

Post a Comment