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