简体   繁体   中英

How to Handle HTTP Basic Auth headers in Selenium Webdriver using Java ?

How to handle Http Basic Auth headers in Selenium Web-driver using Java? I used this format **driver.get("http://username:password@url.com/login")** to handle Http basic Authentication when Authentication dialog appears first time but it prompt again after Website Login request submitted to server but the Approach i used earlier is not working after Login Scenario.

Help would really Appreciated Thanks

Try using Alert.authenticateUsing(Credentials) to handle the authentication dialog:

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

With BrowserMob you can create a proxy which sets the Authentication Header to the request.

<dependency>
    <groupId>net.lightbody.bmp</groupId>
    <artifactId>browsermob-core</artifactId>
    <version>2.1.5</version>
    <scope>test</scope>
</dependency>

Start the Proxy and configure the webdriver

public static WebDriver getWebdriver() {
    BrowserMobProxyServer proxy = new BrowserMobProxyServer();

    // Adds Filter to manipulate the request header
    proxy.addRequestFilter((request, contents, messageInfo) -> {
        // Create the Base64 String for authorization
        String authHeader = "Basic " + Base64.getEncoder().encodeToString(("user:password");
        // Set the Authorization header to the request
        request.headers().add("Authorization", authHeader);
        return null;
    });
    proxy.start(0);

    ChromeOptions options = new ChromeOptions();
    // Get the Selenium proxy object
    Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
    // To manipulate requests for local host
    seleniumProxy.setNoProxy("<-loopback>");
    options.setProxy(seleniumProxy);
    // Initialize the webdriver with the proxy settings
    return new ChromeDriver(options);
}

To stop the proxy simply call

proxy.stop();

Try This .....

     try{ 
        String webPage = "http://www.domain.com/";
        String Uname = "admin";
        String password = "admin";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        }

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