How to Handle Browser Authentication using Selenium java?
Last Updated :
23 Jul, 2025
Handling browser authentication using Selenium Java is a common requirement when automating web applications that require login credentials to access specific sections. In many cases, websites prompt for basic authentication with a pop-up window, which Selenium WebDriver can't interact with directly as it handles browser content, not browser-level dialogs. To bypass this, a common approach is to embed the credentials directly in the URL or use specialized techniques like AutoIT or Robot class.
By automating browser authentication, testers can streamline test scenarios that involve secure pages, enhancing the efficiency of Selenium automation.
Setting Up Your Environment
Before diving into handling browser authentication, ensure you have the following setup in place. If you don't have Selenium and ChromeDriver in your machine then you have to download it first.
Selenium
Go to https://www.selenium.dev/downloads/ and download the java selenium. A zip file will be downloaded then extract the zip file. After extracting the file , if you look into folder you will find a bunch of .jar file.
ChromeDriver
Go to https://googlechromelabs.github.io/chrome-for-testing/ and download CromeDriver according to your Chrome version. Again this is also a zip file , extract all.
Project SetUp
- Go to IntelliJ IDEA or Eclipse and Create a new Project named it whatever you want.Create a package inside the Source folder and inside that package Create a .java file where we will write all our logic.
- Now go to location we you had the extracted selenium folder , it will look something like this chromedriver-win64 (for windows). Copy all the .jar files inside of this folder. Then go to Intellij and click on project structure,then go to modules and add all the .jar files and save.
Understanding Browser Authentication Types
Basic , Digest and Form-based authentiation are alternative authentication mechanisms which are popular in web applications. Basic authentication is often used with stateless clients which pass their credentials on each request. It's quite common to use it in combination with form-based authentication where an application is used through both a browser-based user interface and as a web-service.
Basic Authentication
In basic Authentication, we will be using base 64 encoding for generating our cryptographic string which contains the information of username and password. Please note we can use any of the encoding techniques like URL, Hexadecimal, or any other we want.
Features:
- Easy to implement
- High risk as user credentials are passed as plain text
- No server side configuration needed.
Digest Authentication
An alternative to the basic authentication method is the digest authentication, which ensures security during data transmission. Contains a hashing technique to protect credentials in transit. Additionally, it ensures data integrity.
Features:
- Provides better security compare to basic authentication approach.
- It requires additional server side configuration.
- It complex to implement.
Form-based Authentication
In form-based authentication, users credentials are sent as plain text and the destination server is not authenticated. This form of authentication can expose your usernames and passwords if all connections are not over SSL. If username and password information is transmitted, it can be easily deciphered.
Features:
- Ability to use form-based authentication in mobile applications, although it’s best suited for desktop and web environments.
- Can be combined with other authentication methods (e.g., OAuth, OpenID Connect).
- Requires server-side processing to handle form submission and authentication.
To handle authentication in Selenium , we will use this demo test website: https://the internet.herokuapp.com/basic_auth .Navigating this gives us an alert/popup like the one below.
https://the-internet.herokuapp.com/basic_authHandling Basic Authentication
In case of Basic authentication, users credentials will be encoded into cryptographic string using Base64 encoder, which contains the information of username and password. However this is not a secure implementation as encoded string can be decoded easily and transmits the password as plain text is also not a good option either.
Java
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v126.network.Network;
import org.openqa.selenium.devtools.v126.network.model.Headers;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
public class Browser_Auth_DevTool {
public static void main(String[] args) {
// Setup Chrome driver
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
// Get the devtools from the running driver and create a session
System.out.println("Creating Chrome DevTools session");
DevTools devTools = driver.getDevTools();
devTools.createSession();
// Enable the Network domain of devtools
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
// Encoding the username and password using Base64
String auth = "admin:admin";
String encodeToString = Base64.getEncoder().encodeToString(auth.getBytes());
System.out.println("Encoded String: " + encodeToString);
// Pass the network header directly as Authorization: Basic <encoded String>
Headers headers = new Headers(Map.of("Authorization", "Basic " + encodeToString));
devTools.send(Network.setExtraHTTPHeaders(headers));
// Navigate to the website
driver.get("https://the-internet.herokuapp.com/basic_auth");
// Verify the loaded page
String title = driver.getTitle();
System.out.println("The page title is : " + title);
String text = driver.findElement(By.tagName("p")).getText();
System.out.println("The text present in page is : " + text);
}
}
Output
Handling Digest Authentication
Digest authentication on the other hand uses encryption. Below code shows how to handle digest Authentication using Selenium WebDriver.In this process user credentials will get hashed first before sending them to the server which makes them more secure than basic authentication.
Java
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Form_Based_Auth {
public static void main(String[] args) {
// Use Selenium to automate browser actions
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
try{
((HasAuthentication)driver).register(UsernameAndPassword.of("admin","admin"));
driver.get("https://the-internet.herokuapp.com/digest_auth");
// Verify if page is loaded successfully
String Title = driver.findElement(By.tagName("h3")).getText();
String text = driver.findElement(By.tagName("p")).getText();
System.out.println(Title);
System.out.println(text);
}catch (NoSuchElementException e){
System.out.println("Element not found: " + e.getMessage());
}catch(WebDriverException e){
System.out.println("WebDriver error: "+ e.getMessage());
}catch(Exception e){
System.out.println("An unexpected error: " + e.getMessage() );
}finally {
driver.quit();
}
}
}
Output
Digest_AuthenticationHandling Form-Based Authentication
Form-based authentication is a common method for securing web applications, where users must enter their credentials (username and password) into a form on a webpage. Selenium WebDriver provides a straightforward way to automate this process by interacting with web element.
here's the implementation -
Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Form_Auth {
public static void main(String[] args) {
// Setup WebDriver
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// Navigate to the login page
driver.get("https://practicetestautomation.com/practice-test-login/");
// Locate username and password fields
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
// Enter the credentials
usernameField.sendKeys("student");
passwordField.sendKeys("Password123");
// Locate and click the login button
WebElement loginButton = driver.findElement(By.id("submit"));
loginButton.click();
// Optionally verify if login was successful or not
String pageTitle = driver.getTitle();
System.out.println();
if(pageTitle.equals("Logged In Successfully | Practice Test Automation") ) {
System.out.println("Congratulations student. You successfully logged in!");
} else {
System.out.println("Login Failed");
}
// Quit the browser
driver.quit();
}
}
Output
Form Based AuthenticationConclusion
Browser authentication in Selenium Java can be tackled using several methods depending on the specific scenario. Embedding credentials in the URL is the simplest approach, but other techniques like handling pop-ups using external tools may be required for more advanced use cases. Mastering this will help create robust automated test cases for secure websites, ensuring seamless interaction with authenticated pages during testing.
By efficiently handling browser authentication in Selenium, testers can save time and improve test reliability for applications that require login credentials.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING