Introduction
There are instances where you would work with applications that have their security behind the basic HTTP Authentication, also known as the Basic Authentication. Before you can be granted access to these sites or apps, you will be required to run some credentials through the website where you are requesting a page. If you cannot run those credentials through the website, you will have to deal with a pop up at a system level that prompts users for a username and password. This situation renders your Selenium helpless.
In the initial versions before Selenium 2, it is possible to execute it through the injection of credentials into a custom header. However, due to some advancements, another way to go about this is the Browsermob proxy, which is quite complex. We will discuss a simpler way here.
It is essential to recognize that the basic authentication feature is still working correctly with geckodriver v0.18.0, Mozilla Firefox 53.0, Selenium 3.4.0, Google Chrome 60.x, and chromedriver v2.31.488763, through Selenium Java bindings. This is a tested and working code that successfully opens using a valid set of credentials to access the URL.
For Mozilla Firefox,
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class BasicAuthentication_FF { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.navigate().to("http://admin:admin@the-internet.herokuapp.com/basic_auth"); } }
For Chrome,
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class BasicAuthentication_Chrome { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); options.addArguments("disable-infobars"); options.addArguments("--disable-extensions"); WebDriver driver = new ChromeDriver(options); driver.navigate().to("http://admin:admin@the-internet.herokuapp.com/basic_auth"); } }
You should note that the basic authentication via URL is blocked only for sub-resources, thus creating the possibility of using it on the domain as follows:
driver.get("http://admin:admin@localhost:8080"); driver.get("http://localhost:8080/project");
It is also possible to create a small extension to automatically set the credentials when they are requested as follows:
options = webdriver.ChromeOptions() options.add_extension(r'C:\dev\credentials.zip')