Basic Authentication with Mock Data

Lesson Overview

Welcome! Today's lesson is about a key aspect of web security — Authentication.

Simply put, authentication verifies your identity when you log into a site. It ensures that you are who you claim to be.

Setting Up Express and Creating Mock Users

Let's dive into implementing Basic Authentication using mock data in an Express.js server.

const express = require('express');
const app = express();

// Mock users
const USERS = {
  'Alice': 'password123',
  'Bob': 'password456',
};

Set up the express application and define a USERS object as a mock user database.

Middleware for Authentication

Now, let's implement a middleware that is executed before every HTTP request and that checks the Authorization header, and validates credentials:

app.use((req, res, next) => {
  const auth = req.headers['authorization'];

  if (!auth) {
    return res.status(401).send('No credentials provided');
  }

  const [username, password] = Buffer.from(auth.split(' ')[1], 'base64').toString().split(':');
  
  if (USERS[username] !== password) {
    return res.status(403).send('Forbidden');
  }

  next();
});

In this middleware, we extract the Authorization header and decode its Base64 content to retrieve the username and password. If the credentials are missing or invalid, we return a 401 Unauthorized or 403 Forbidden status. If they are valid, we allow the request to proceed by calling next().

Understanding Base64 Encoding:

Base64 is a method for encoding binary data (e.g., a username and password) into an ASCII string format using 64 different characters. This is commonly used to ensure that data remains intact when transmitted over mediums that only support text. When using Basic Authentication, the Authorization header contains credentials in the form of Base64, which the server needs to decode to retrieve the username and password.

  1. Check for the Authorization header.
  2. Decode Base64 credentials with Buffer.from(auth.split(' ')[1], 'base64').toString().split(':').
  3. Validate against the USERS object.

Please note that this is a very insecure way of doing things, as technically you send a raw password over the network. This example is just for demonstration purposes and is not how you should implement authentication in real-life applications. Always use secure methods like HTTPS and consider more secure authentication mechanisms, such as token-based authentication.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal