java - 为 Selenium 创建 HTTP Basic auth Chrome 扩展(MWE 可用)

标签 java google-chrome selenium

我正在尝试使用 Google Chrome 运行 Selenium 测试。我希望使用 HTTP 基本身份验证登录。这在 Selenium 中没有实现,所以建议加载一个扩展。我正在使用来自

的代码

https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxythe answer to "How to override basic authentication in selenium2 with Java using chrome driver?"

我已尝试使其适应我的需要。

更新

检查最小工作示例。

git clone git@github.com:alexbiddle/selenium-chrome-http-basic-auth.git

摘录如下

var config = {
    mode: "fixed_servers",
    rules: {
      singleProxy: {
        scheme: "https",
        host: "subdomain.example.com"
      },
      bypassList: ["foobar.com"]
    }
  };

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

function callbackFn(details) {
    return {
        authCredentials: {
            username: "example",
            password: "abc123"
        }
    };
}

chrome.webRequest.onAuthRequired.addListener(
        callbackFn,
        {urls: ["<all_urls>"]},
        ['blocking']
);

使用 Java 加载它

ChromeOptions chromeOptions = new ChromeOptions();
File proxyPath = new ClassPathResource("proxy.zip").getFile();
chromeOptions.addExtensions(proxyPath);

DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CAPABILITY, chromeOptions);
webDriver = new ChromeDriver(capability);

我在 https://developer.chrome.com/extensions/proxy#type-ProxyServer 仔细检查了文档以防万一缺少某些值,但是在使用 URL 加载测试时

https://subdomain.example.com

它失败了

ERR_TUNNEL_CONNECTION_FAILED

我在 Mac 上使用 Chrome。

最佳答案

错误可能是由于您的扩展程序定义的代理造成的。

如果您需要与系统不同的代理,您应该在没有代理的情况下构建扩展并在功能中定义代理。

要创建扩展,只需使用您在 usernamepassword 中定义的凭据压缩以下文件:

list .json:

{
  "manifest_version": 2,
  "name": "Authentication for ...",
  "version": "1.0.0",
  "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"],
  "background": {
    "scripts": ["background.js"]
  }
}

background.js :

var username = "my-username";
var password = "my-password";

chrome.webRequest.onAuthRequired.addListener(
  function handler(details) {    
    if (username == null)
      return {cancel: true};

    var authCredentials = {username:username, password: username};
    username = password = null;

    return {authCredentials: authCredentials};
  },
  {urls: ["<all_urls>"]},
  ['blocking']
);

关于java - 为 Selenium 创建 HTTP Basic auth Chrome 扩展(MWE 可用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458165/

相关文章:

javascript - 为 Chrome 扩展程序指定 native 消息传递主机

JavaScript React 在源选项卡中隐藏源文件

java - Selenium Web 驱动程序 : Handle Confirm Box using Java

java - 在 EMF Compare 计算的 ADD Diff 中检索 "match of value"

java - 尝试打印二维数组(矩阵)时出错

Java selenium 无法发送按键和单击元素

java - Selenium Web 驱动程序测试 Web 元素已更新

java - 如何从 ConcurrentHashMap<String, Set<String>> 中删除用作值的 Set?

html - Chrome 如何知道我的地理位置?

java - 如何在不同的 URL 上使用 Selenium 和 JUnit 5 运行整个测试套件