Handling Browser Authentication using Selenium


We can handle browser authentication with Selenium webdriver. We have to pass the credentials appended with the URL. The username and password must be added with the format: https://username:password@URL. Let us make an attempt to handle the below browser authentication.

Once the User Name and Password are entered correctly and the OK button is clicked, we are navigated to the actual page with the text Congratulations! You must have the proper credentials.

Syntax

https://username:password@URL
https://admin:admin@the−internet.herokuapp.com/basic_auth

Here, the username and password value is admin.

URL is www.the−internet.herokuapp.com/basic_auth

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrwAuthnPopup{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String a = "admin";
      // appending username, password with URL
      String s = "https://" + a + ":" + a + "@" +
      "the-internet.herokuapp.com/basic_auth";
      driver.get(s);
      // identify text
      String m = driver.findElement(By.cssSelector("p")).getText();
      System.out.println("Text is: " + m);
      driver.close();
   }
}

Output

Updated on: 04-Mar-2024

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements