简体   繁体   中英

How to handle Authentication header in Selenium?

I am new to selenium and trying to handle authentication header which had been put up on web end for security reason. I am trying to access the site and send data using url using selenium but as authentication is required, I am unable to do so. I've tried below mentioned code but couldn't succeed.

//Selenium-WebDriver Java Code for entering Username & Password as below:
    driver.findElement(By.id("userID")).sendKeys("username");
    driver.findElement(By.id("password")).sendKeys("pass");
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();*/
        //self.headers = { "Authorization": "Basic xyz=" };
  /*        driver.switchTo().window("Authentication Required");
        driver.findElement(By.id("userID")).sendKeys("username");
        driver.findElement(By.id("password")).sendKeys("pass");*/

        //selenium.start("addCustomRequestHeader=true");
        //selenium.windowMaximize();
        //selenium.addCustomRequestHeader( "Authorization","Basic "+"xyx=" );

Any help or suggestion would do great. Thanks in advance.

The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication.

WebDriverWait wait = new WebDriverWait(driver, 10);      
Alert alert = wait.until(ExpectedConditions.alertIsPresent());     
alert.authenticateUsing(new UserAndPassword(username, password));

Please go through this link if you want to enable authentication

http://seleniumwebdrivertrainings.com/how-to-perform-basic-authentication-for-firefoxdriver-chromedriver-iedriver-in-selenium-webdriver/

This is my Java code:

public class LoginPage {

private WebDriver driver;

public LoginPage(WebDriver driver) {
    this.driver = driver;
}

public void login(){
    driver.get("http://localhost:8080/projectLogin/");

    WebElement username = driver.findElement(By.name("iDElementHtmlUser"));
    WebElement pass = driver.findElement(By.name("iDElementHtmlPassword"));

    username.sendKeys("rivanMota");
    pass.sendKeys("1234");
    username.submit();

    boolean logged = driver.getPageSource()
            .contains("idLogged"); // some id that only exists on logged page.
    assertTrue(logged); // True if login success
}
}

And HTML:

<input id="iDElementHtmlUser" type="text" name="username" />
<input id="iDElementHtmlPassword" type="password" name="password" />

That is all folks!

Try this,

WebDriver driver = new ChromeDriver(); 

String baseUrl=”http://” + “USERNAME” + “:” + “PASSWORD” + “@” + “xyz.com”; 

driver.get(baseUrl + “/”);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM