Q21 of 37 · Selenium

How do you handle authentication popups (basic auth) in Selenium?

SeleniumMidseleniumauthenticationbasic-authcdp

Short answer

Short answer: Most reliable: embed credentials in the URL — `https://user:pass@host/path`. For Chromium, use Chrome DevTools Protocol's `Network.setExtraHTTPHeaders` with a base64 Authorization header. Avoid trying to type into the native dialog — Selenium can't drive it directly.

Detail

HTTP Basic Auth pops up a native browser dialog that lives outside the page DOM, so Selenium's normal element handling doesn't apply. There are three working approaches.

1. URL-embedded credentials (simplest):

driver.get("https://user:pass@staging.example.com/admin");

The browser sends the Authorization: Basic ... header automatically and the dialog never appears. Caveats:

  • Chrome long ago deprecated this for cross-origin subresource requests, but top-level navigation still works.
  • The credentials end up in browser history and the address bar — fine for tests, not for prod-like setups.

2. Chrome DevTools Protocol (Selenium 4):

ChromeDriver chrome = (ChromeDriver) driver;
DevTools devTools = chrome.getDevTools();
devTools.createSession();

String basic = Base64.getEncoder().encodeToString("user:pass".getBytes());
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.send(Network.setExtraHTTPHeaders(
    new Headers(Map.of("Authorization", "Basic " + basic))
));

driver.get("https://staging.example.com/admin");

This adds the auth header at the network layer for every request, sidesteps the dialog, and works with embedded resources. Chrome/Edge only.

3. Selenium 4's Actions can sometimes type into the dialog if the OS supports it, but this is unreliable across browsers — don't bet on it.

The pragmatic ranking: try URL-embedded first; if Chrome blocks it for your setup, switch to CDP. Prefer asking the dev team to provide a token-based test login instead — basic auth is awkward enough that automating around it is rarely the long-term answer.

// WHAT INTERVIEWERS LOOK FOR

URL-embedded creds as the first answer, awareness of CDP setExtraHTTPHeaders for tougher cases, and recognition that the native dialog isn't directly drivable from Selenium.

// COMMON PITFALL

Trying to switchTo().alert() on a basic-auth dialog — that's a JS alert handler, not OS dialog. Or assuming creds-in-URL works for every fetch (it doesn't for cross-origin XHRs in modern Chrome).