/ node

The Magic Behind Basic HTTP Authentication

Basic Auth PromptIt's very easy to take things for granted as a developer. We almost always try and use libraries for every and anything to not reinvent the wheel. As I continue to grow, I find myself with a desire to dig deeper and understand the "black boxes" I've come to know.

Recently, a beginner friend came to me needing a very simple authentication system. I told him about basic HTTP authentication to which he replied, "Sounds cool! How does it work?" I realized I had no idea and pulled up the spec. This one's for you, Zack!

When a request is made to a basic HTTP auth protected endpoint, the server first looks for a specific header:

Authorization: Basic dXNlcjpwYXNz

Where dXNlcjpwYXNz is actually a base64 encoded username:password string. For our example, we'll use the username user and password pass. Here's what that looks like (the -n prevents a new line character from being added):

$ echo -n "user:pass" | openssl base64

If the header is not present, the server will send back a challenge header and HTTP status code 401 (Unauthorized).

WWW-Authenticate: Basic realm="Message to display"

This is all it takes to make the browser magically display the sign-in prompt!

Upon submission, the server will do the encoding and resubmit the request with the header!

Here's a full example for express. And you know what? Let's add the sendgrid-node library to email us with the IP address of unauthorized attempts!

Create the file app.js and install our dependencies,

npm install express sendgrid

Now run it, node app.js, and visit localhost:3000 in your browser!

Be sure to reach out on twitter if you have any questions!

This post was originally written for and posted to the SendGrid Blog