Skip to main content

How to Access Basic Auth

Intro​

In this guide, you will learn how to pass credentials to a site when requesting a page that is secured behind Basic HTTP Authentication.

Sometimes you'll work with applications that are secured behind Basic HTTP Authentication (a.k.a. Basic Auth). In order to access them you'll need to pass credentials to the site when requesting a page otherwise you'll get a system level pop-up prompting you for a username and password -- rendering Selenium helpless.

Before Selenium 2 we were able to accomplish this by injecting credentials into a custom header, but now a popular way to do it is using something like BrowserMob Proxy. Some people are also solving this issue with browser specific configurations but those methods feel a little heavy and complicated.

Instead, let's use a more straightforward approach that is browser agnostic and quick to setup.

A Solution​

By specifying the username and password in the URL when visiting a page with Selenium, we can a side-step the system level dialog box and avoid setting up a proxy server. This approach will work for both HTTP or HTTPS pages.

Example​

NOTE: We are using a Basic Auth example found on the-internet. The username and password are both admin.

There are two tests:

  • Credentials in the URL: we load the page by passing in the username and password in the front of the URL (e.g., https://admin:admin@). Once it loads we grab text from the page to make sure we ended up in the right place.
  • Credentials cached by the browser: alternatively, we could access the page with credentials once (e.g., as part of the test setup). This caches the Basic Auth session in the browser, enabling us to visit the page again without having to specify credentials. This is particularly useful if you have numerous pages behind Basic Auth.

NOTE: If your application serves both HTTP and HTTPS pages from behind Basic Auth then you will need to load one of each type before executing your test steps. Otherwise you will get authorization errors when switching between HTTP and HTTPS because the browser can't use Basic Auth credentials interchangeably (e.g., HTTP for HTTPS and vice versa).

Expected Behavior​

For the first test:

  • Open the browser
  • Visit the page using Basic Auth
  • Get the page text
  • Assert that the text is what we expect
  • Close the browser

For the second test:

  • Open the browser
  • Visit the page using Basic Auth
  • Navigate to the Basic Auth page again (without providing credentials)
  • Get the page text
  • Assert that the text is what we expect
  • Close the browser

Summary​

Hopefully this tip will help save you from getting tripped by Basic Auth when you come across it.

Happy Testing!

Special Thanks​

Roman Isko
Contributed the initial Java code for this tip.

Authors​

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer