Selenium Java - Handle Browser Authentication Popup

Selenium Java - Handle Browser Authentication Popup
Introduction
In this blog, we'll dive into how to manage browser authentication popups using Selenium WebDriver with Java. This method is super handy when you're automating test cases that need to deal with HTTP basic authentication dialogs.
Handling Browser Authentication Popup
Below is a complete Selenium code example that demonstrates how to bypass browser authentication popups by embedding credentials in the URL.
java
package sa.Demo.SeleniumPractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Selenium_080 {
/****
* Sample Code Definition :- Selenium - Browser Authentication Popup
* Developed By :- Pankaj Kumar
* Date of Creation :- 15-June-2024
* Project :- SAJVSAUTO - Java [Web / Mobile / API]
* SA_BLOG_CODE :- SAJVSAUTO_080
*/
@Test
public void Selenium_080() throws InterruptedException {
System.out.println("Selenium - Browser Authentication Popup");
// Open Chrome Browser
WebDriver driver = new ChromeDriver();
// Maximize the Browser Window
driver.manage().window().maximize();
// Set the username
String username = "admin";
// Set the password
String password = "admin";
// Open the URL with embedded credentials
String URL = "https://" + username + ":" + password + "@" + "the-internet.herokuapp.com/basic_auth";
driver.get(URL);
// Wait for 5 Seconds
Thread.sleep(5000);
// Get The Title of the Page
String title = driver.getTitle();
System.out.println("The page title is " + title);
// Verify the Text in Page
String text = driver.findElement(By.tagName("p")).getText();
System.out.println("The text present in page is ==> " + text);
// Wait for 5 Seconds
Thread.sleep(5000);
// Quit the Driver
driver.quit();
}
}
Explanation
Browser Setup: Configures ChromeDriver and maximizes the browser window.
Authentication Credentials: Embeds the username and password directly into the URL in the format:
https://username:password@host
.Page Interaction:
Opens the authentication-protected page with credentials.
Retrieves the page title and verifies the presence of expected text in the page.
Thread.sleep(): Adds delays for observation (optional for actual test execution).
Driver Cleanup: Properly closes the WebDriver session.
Conclusion
By adding credentials directly into the URL, you can easily manage browser authentication popups in Selenium WebDriver. This approach makes testing pages with HTTP basic authentication straightforward, helping your test cases run smoothly.
Subscribe to my newsletter
Read articles from Pankaj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
