The Gate

http basic authentication with selenium

I want to automate a login page. This page requires the user to log in with basic http authentication. I want to automate this page that has http basic authentication with selenium.

Our application requires to log in. After the user is logged in, he can click on a link in a menu. Then a new tab page opens with another web application. This web application requires some basic http authentication. There is a popup visible that requires the user to log in with a user and a password.

A real person fills in the required fields, the User Name and his password to log in. We try to fake a user with our selenium script. The first thing we want is that our script fills in the same fields. But this is not possible in selenium.

I searched a lot how to solve this problem. The only solution I found is that the script have to go to a url with the user and password in the url itself.

http://<user>:<pwd>@the.url.to.go/

Therefore I wrote a function in our framework that fetches the current url and adds the user and password to it.

String appendUserAndPasswordToUrl() throws MalformedURLException {
    URL current_url = new URL(driver.getCurrentUrl());
    String host_part = CucumberConfig.getInstance().getUsername() +
                       ":" + CucumberConfig.getInstance().getPassword() +
                       "@" + current_url.getHost() +
                       current_url.getFile() +
                       "#" +  current_url.getRef();
    return current_url.getProtocol() + "://" + host_part;
}

driver.get(this.appendUserAndPasswordToUrl());

With this little code I managed to go to the application when the user clicks on the link. The script executes the following steps:

  • The script clicks on the link
  • The url opens with the popup in a new tab page
  • The scripts activates the tab page
  • The script reloads the url with the credentials
  • The script can continue now

With this simple trick it is possible to enter a web page that opens via a click. The script needs to reload the page that opens. Http basic authentication with selenium, it is possible.

About the author

I currently work as a Test Automation Consultant at b.ignited. Here I work for different clients in different industries to help them start and speed up their testing cycles

I’ve been testing software since 2000 when I became involved in testing telephone applications and hardware. Since then, I’ve been able to expand my experience by testing a variety of embedded, web, mobile and desktop applications. I have used various development methodologies from waterfall to agile.

I consider myself to be a lifelong learner.