Basic HTTP authentication in Elixir/Phoenix

Let’s look on what HTTP Basic authentication is and how to implement and test the HTTP Basic authentication in a Phoenix web application.

Basic is one of the authentication schemes we can use to authenticate access on the web (other is for example a Bearer scheme for OAuth 2.0 tokens). Using the Basic scheme is very simple. If our server responds with 401 Unauthorized response including WWW-Authenticate response header with a Basic challenge as follows:

WWW-Authenticate: Basic realm="Access to the application"

the browser can automatically ask the user for login credentials (login and password). The browser then connects the user and password together (separated by colon) and uses Base64 encoding to create a single string that is provided in the request Authorization header:

Authorization: Basic am1lbm9oZXNsbw==\n

One important thing to realize is that this header will now be sent by browser automatically with subsequent requests as long as they remember it (until browser restarts). Secondly that encoding password using Base64 is not a security feature and you need HTTPS.

Usually, we don’t dig the details of this challenge as authentication libraries or frameworks do this for us. In Elixir world we can reach for BasicAuth plug:

# mix.exs
...
{:basic_auth, "~> 2.2.2"}
...

Once added, fetched, and compiled we can use it as any other plug in the Phoenix router:

Of course it’s up to you to make sure that a user with such credentials exist during the test run.

If we want to provide a “log out” option for the users, we can do so by sending wrong credentials to a protected resource (but they will see a new login popup).

Finally, if you are authorizing users to manipulate data on the server, make sure to use CSRF protection, because as I stated in the beginning, the Authorization header is sent automatically by the browser.