15. Handling Basic Authentication Using Webdriver

Here is post which explains you how to handle basic authentication.


Problem:

Some of the applications that are secured with Basic Authentication. If you want to access those applications first you need to pass credentials. Those applications will launch a system level pop-up which cant not be handled by selenium.

If you access below url it will ask for authentication.

http://the-internet.herokuapp.com/basic_auth

Solution:

By specifying userName and password in URL when accessing the page we can avoid system level dialog. This approach will work for HTTP and HTTPS pages.


package Others;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class authentication {
       public WebDriver driver;
       @Test
       public void testBasicAuth() {
              //UserName --admin
              //Password --admin
              //URL --- http://the-internet.herokuapp.com/basic_auth
              //Updated URl -- http://admin:admin@the-internet.herokuapp.com/basic_auth
              driver.get("http://admin:admin@the-internet.herokuapp.com/basic_auth");
              //assert Text
              String actualText=driver.findElement(By.xpath("//div[@class='example']/p")).getText();
              Assert.assertEquals(actualText, "Congratulations! You must have the proper credentials.");
              System.out.println("Test passed");
       }
       @BeforeClass
       public void beforeClass() {
              System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32\\chromedriver.exe");      
              driver = new ChromeDriver();
              driver.manage().window().maximize();
              driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       }

       @AfterClass
       public void afterClass() {
              driver.quit();
       }


}

No comments:

Post a Comment