【发布时间】:2016-03-01 14:54:22
【问题描述】:
如何使用 Java 处理 Selenium Web-driver 中的 Http Basic Auth headers?
我使用了这种格式**driver.get("http://username:password@url.com/login")**
首次出现身份验证对话框时处理 Http 基本身份验证,但在网站登录请求提交到服务器后再次提示,但我之前使用的方法在登录场景后不起作用。
帮助真的很感激 谢谢
【问题讨论】:
如何使用 Java 处理 Selenium Web-driver 中的 Http Basic Auth headers?
我使用了这种格式**driver.get("http://username:password@url.com/login")**
首次出现身份验证对话框时处理 Http 基本身份验证,但在网站登录请求提交到服务器后再次提示,但我之前使用的方法在登录场景后不起作用。
帮助真的很感激 谢谢
【问题讨论】:
使用BrowserMob,您可以创建一个代理,将身份验证标头设置为请求。
<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();
【讨论】:
尝试使用Alert.authenticateUsing(Credentials) 处理身份验证对话框:
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
【讨论】:
试试这个.....
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);
}
【讨论】: