https://a.storyblok.com/f/283157/1920x800/a07f1bb085/basic_auth.jpg

What is Basic Auth? With ExpressJS example

Published: Oct 6, 2024

Sometimes you have to protect your website from unwanted access. There are many options you can choose from. One option is the so-called "basic auth," which uses the "Authorization" header in your HTTP request to verify whether you are allowed to fetch the resource or not.

In this blog post, I want to show you what basic auth is, what the pros and cons of it are, and how you can implement it in your Express.js application.

• • •
• • •

Introduction to Basic Authentication

Basic auth uses the "Authorization" header (more info here). The header consists of the schema and the credentials.

In basic auth, the schema is "Basic" and the credentials are base64-encoded username and password, which are combined with a colon (:).

// Username: admin
// Passwort: pass
// base64("admin:pass") = "YWRtaW46cGFzcw=="
Authorization: Basic YWRtaW46cGFzcw==

The server receives the credentials and can grant access to resources.

One special thing about basic auth is that virtually all browsers can handle these requests. They detect when authorization using basic auth is required (the first response is a 401 with a specific header in the response) and prompt a small login screen, which then adds the authorization for subsequent requests.

This makes restricting access to resources very easy because you don't have to implement anything in the frontend. The browser is capable of handling this kind of authorization.

Drawbacks of basic auth

While basic auth is a very easy-to-use authorization technique, it also has some drawbacks.

You cannot create your own login screen because the login is provided by your browser before fully accessing the web page. It is fine for test systems or private projects, but for larger projects, other authorization implementations are recommended.

A second drawback is that, in my experience, basic auth configurations are often static. For example, you might use a file where the credentials are listed. However, when you want to build a larger website with a user base, you'll want to manage your logins using a database.

Basic Auth Realms

Realms are a way to separate authentication areas within a single application. It is an additional name for the area. Realms can have different sets of credentials, and modern browsers are capable of handling those.

After requesting a page without credentials, the website will give an HTTP status code 401 Unauthorized response with the Header "WWW-Authenticate" set. This header contains the realm name.

WWW-Authenticate: Basic realm="protected area"

For example, you could create two areas of your website, which should be accessed by two separate groups of users. You could then differentiate the groups using the realm option.

The realm has to be set in most libraries, but usually a generic name is given. It also does not appear on most login forms.