Handling Authentication Popup in Selenium
HTTP Basic Authentication popups (the browser-native username/password dialog) are not regular HTML elements — they are OS-level dialogs that Selenium handles differently.
Method 1 — Embed credentials in URL (simplest):
// Format: http://username:password@website.com
driver.get("http://admin:password@the-internet.herokuapp.com/basic_auth");
Method 2 — WebDriverWait + authenticateUsing:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword("username", "password"));
Full example:
import org.openqa.selenium.Alert;
import org.openqa.selenium.security.UserAndPassword;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Test
public void handleAuthPopup() {
driver.get("https://the-internet.herokuapp.com/basic_auth");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for the auth popup to appear
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// Pass credentials
alert.authenticateUsing(new UserAndPassword("admin", "admin"));
// Verify successful login
Assert.assertTrue(driver.getPageSource().contains("Congratulations"));
}
Method 3 — ChromeOptions with authentication extension:
// For newer Chrome versions, use DevTools Protocol
ChromeDriver chromeDriver = (ChromeDriver) driver;
Map<String, Object> params = new HashMap<>();
params.put("origin", "https://the-internet.herokuapp.com");
params.put("username", "admin");
params.put("password", "admin");
chromeDriver.executeCdpCommand("Network.setExtraHTTPHeaders", params);
Method 4 — AutoIT (for Windows native dialogs): When the popup is truly a Windows OS dialog (not a browser dialog), use AutoIT to handle it externally.
Comparison:
| Method | Works for | Notes |
|---|---|---|
| URL credentials | HTTP Basic Auth | Simplest approach |
authenticateUsing() | Browser auth dialogs | Standard Selenium way |
| AutoIT/Sikuli | OS-level popups | Requires external tool |
Key point: Since there will be a popup for logging in, we need to use the explicit command and verify if the alert is actually present. Only if the alert is present, we pass the username and password credentials.
