Add ssl certificate to selenium-webdriver

家住魔仙堡 提交于 2019-12-05 00:03:49

So apparantly this is not possible with BrowserMob out of the box. I therefore wrote a proxy extension SeleniumSslProxy that can be plugged into Selenium and adds certificate based authentication to create a HTTPS connection.

This is how it works:

  • intercept Selenium HTTP requests with BrowserMob
  • setup an SSLContext given a certificate (.pfx file) and password
  • use okhttp to forward the request to the target URL
  • convert the okhttp Response to a netty FullHttpResponse so it can be handled by Selenium

You can find the code on github. Here's an example how it can be used in Selenium end-to-end tests (also works in headless mode):

@Before
public void setup() {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    File clientSslCertificate = new File(
        classLoader.getResource("certificates/some-certificate.pfx").getFile());
    String certificatePassword = "superSecret";

    this.proxy = new SeleniumSslProxy(clientSslCertificate, certificatePassword);
    this.proxy.start();

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setProxy(proxy);
    this.webDriver = new ChromeDriver(chromeOptions);
}

@Test
public void pageTitleIsFoo() {
    // given
    String url = "http://myurl.lol";
    // NOTE: do not use https in the URL here. It will be converted to https by the proxy.

    // when
    this.webDriver.get(url);
    this.webDriver.manage().timeouts().implicitlyWait(5, SECONDS);

    // then
    WebElement title = this.webDriver.findElement(By.className("title"));
    assertEquals("Foo", title.getText());
}

@After
public void teardown() {
    this.webDriver.quit();
    this.proxy.stop();
}

Note that I only used chromeDriver and never tested it with other drivers. Minor adjustments to the SeleniumSslProxy might be necessary to be used with other drivers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!