繁体   English   中英

如何使用 Java 在 Selenium Webdriver 中处理 HTTP Basic Auth 标头?

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

如何使用 Java 处理Selenium Web 驱动程序中的Http Basic Auth 标头 我使用这种格式**driver.get("http://username:password@url.com/login")**在第一次出现身份验证对话框时处理 Http 基本身份验证,但在网站登录请求提交到服务器后再次提示但是我之前使用的方法在登录场景后不起作用。

帮助真的很感激谢谢

尝试使用Alert.authenticateUsing(Credentials)来处理身份验证对话框:

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

使用BrowserMob,您可以创建一个代理,将 Authentication Header 设置为请求。

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

启动代理并配置 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);
}

要停止代理只需调用

proxy.stop();

尝试这个 .....

     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);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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