Open In App

How to Handle Browser Authentication using Selenium java?

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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.

form based authentication in Selenium Java
https://the-internet.herokuapp.com/basic_auth

Handling 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

output of Handling Digest Authentication
Digest_Authentication

Handling 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

Screenshot-2024-09-17-023056
Form Based Authentication

Conclusion

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.


Article Tags :

Similar Reads