</>

Technology

Scenario-Based

Difficulty

Advanced

Interview Question

How do you handle basic authentication pop-ups in Selenium?

Answer

Handling Basic Authentication Pop-ups in Selenium

Browser-level HTTP Basic Auth dialog boxes are OS-level prompts that Selenium cannot interact with using switchTo().alert(). Here are the proper approaches:

Method 1 — Credentials in URL (Simplest)

Java
// Format: http://username:password@hostname/path
String url = "https://admin:password123@staging.myapp.com/dashboard";
driver.get(url);

Works well for HTTP Basic Auth on most browsers.

Method 2 — Selenium 4 CDP (Chrome DevTools Protocol)

Java
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v117.network.Network;

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

devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

// Set auth credentials
devTools.send(Network.setExtraHTTPHeaders(
    new Headers(Map.of("Authorization",
        "Basic " + Base64.getEncoder().encodeToString("admin:password123".getBytes())))
));

driver.get("https://staging.myapp.com/dashboard");

Method 3 — ChromeOptions Extension for Auth

Java
// Use with Selenium Grid or proxy auth scenarios
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-blink-features=AutomationControlled");

// Handle via browser extension or proxy settings

Method 4 — WebDriverWait + Alert (Some Browsers)

Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
try {
    Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    // Does NOT work for HTTP Basic Auth in Chrome/Edge
    // Works in some older Firefox versions
    alert.authenticateUsing(new UserAndPassword("admin", "password123"));
} catch (TimeoutException e) {
    System.out.println("No auth popup appeared");
}

Recommended Approach by Browser

BrowserBest Method
Chrome / EdgeCredentials in URL or CDP
FirefoxauthenticateUsing() or URL
Headless (all)Credentials in URL
Selenium GridCDP or URL method

Follow AutomateQA

Related Topics