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.
Let's dive into implementing Basic Authentication using mock data in an Express.js
server.
JavaScript1const express = require('express'); 2const app = express(); 3 4// Mock users 5const USERS = { 6 'Alice': 'password123', 7 'Bob': 'password456', 8};
Set up the express application and define a USERS
object as a mock user database.
Now, let's implement a middleware that is executed before every HTTP request and that checks the Authorization
header, and validates credentials:
JavaScript1app.use((req, res, next) => { 2 const auth = req.headers['authorization']; 3 4 if (!auth) { 5 return res.status(401).send('No credentials provided'); 6 } 7 8 const [username, password] = Buffer.from(auth.split(' ')[1], 'base64').toString().split(':'); 9 10 if (USERS[username] !== password) { 11 return res.status(403).send('Forbidden'); 12 } 13 14 next(); 15});
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.
Authorization
header.Buffer.from(auth.split(' ')[1], 'base64').toString().split(':')
.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.
JavaScript1app.get('/', (req, res) => { 2 res.send('You are authenticated!'); 3});
This route is accessible only to authenticated users.
Express.js
using mock data.Now, you’ll get hands-on with various practice exercises to reinforce these concepts. Let's dive in!