Express.js - REST API with Basic Authentication
Basic Authentication is a simple way to secure REST APIs using a username and password encoded in Base64.
How Basic Authentication Works
- The client sends a request to the server with Authorization header as follows
Basic Base64-encoded(username:password)
- The server decodes the credentials and validates the username and password.
- If valid, the server grants access; otherwise, it returns a 401 Unauthorized error.
Method 1 : Manual Basic Authentication using Authorization Header
This method manually extracts and decodes credentials from the Authorization header
Install Dependencies
Install Express.js with the npm command.
npm install express
Set Up Express.js Server
- This Express.js app implements Basic Authentication using middleware to validate username and password from the Authorization header.
- Only authenticated users can access the /dashboard route, while others receive a 401 or 403 response.
index.js
const express = require('express'); const app = express(); app.use(express.json()); // Credentials const USERNAME = 'admin'; const PASSWORD = '123'; // Middleware for Basic Auth function basicAuth(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader || !authHeader.startsWith('Basic ')) { res.setHeader('WWW-Authenticate', 'Basic realm="Access to protected area"'); return res.status(401).send('Authentication required.'); } const base64Credentials = authHeader.split(' ')[1]; const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii'); const [username, password] = credentials.split(':'); if (username === USERNAME && password === PASSWORD) { next(); // Auth success } else { res.status(403).send('Invalid credentials'); } } // Protected route app.get('/dashboard', basicAuth, (req, res) => { res.send('Welcome to the Dashboard!'); }); // Start server const PORT = 5000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
Run the Server
Run the server using the command is given below.
node index.js
D:\my-app>node index.js Server is running on http://localhost:5000
Output
Access Dashboard Without Authentication
Request:
GET: http://localhost:5000/dashboard
Content-Type: application/json
Response:
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Access to protected area"
Authentication required.
Access Dashboard With Invalid Credentials
- Base64-encoded of admin:admin is YWRtaW46YWRtaW4=
Request:
GET: http://localhost:5000/dashboard
Authorization: Basic YWRtaW46YWRtaW4=
Response:
Status: 403 Forbidden
Invalid credentials
Access Dashboard With Valid Credentials
- Base64-encoded of admin:123 is YWRtaW46MTIz
Request:
GET: http://localhost:5000/dashboard
Authorization: Basic YWRtaW46MTIz
Response:
Status: 200 OK
Welcome to the Dashboard!
Method 2 : Basic Authentication using basic-auth Middleware Package
This method uses the basic-auth npm package to simplify parsing of credentials from the request.
Install Dependencies
Install Express.js and basic-auth with the npm command.
npm install express basic-auth
Basic Express.js Authentication Middleware
- If invalid or missing credentials are provided when accessing /dashboard, the server responds with a 401 Unauthorized status and a WWW-Authenticate header.
- When valid credentials are used, the user receives a JSON response confirming successful access.
index.js
const express = require('express'); const basicAuth = require('basic-auth'); const app = express(); // Middleware for Basic Authentication const auth = (req, res, next) => { const user = basicAuth(req); // Get credentials from the request // Check if credentials are provided and match if (!user || user.name !== 'ram' || user.pass !== '123') { res.set('WWW-Authenticate', 'Basic realm="Authorization Required"'); return res.status(401).send('Unauthorized'); } // If credentials are valid, proceed to the next middleware/route next(); }; // Authenticated Route app.get('/dashboard', auth, (req, res) => { res.json({ message: 'Welcome to Dashboard Page!' }); }); app.get('/user', (req, res) => { res.send('Welcome to the user page!'); }); const PORT = 5000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Run the Server
Run the server using the command is given below.
node index.js
D:\my-app>node index.js Server is running on http://localhost:5000
Output
Access Public User Route
Request:
GET: http://localhost:5000/user
Response:
Status: 200 OK
Welcome to the user page!
Access Dashboard Without Authentication
Request:
GET: http://localhost:5000/dashboard
Response:
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Authorization Required"
Unauthorized
Access Dashboard With Invalid Credentials
- Base64-encoded of user:123 is d3Jvbmc6dXNlcg==
Request:
GET: http://localhost:5000/dashboard
Authorization: Basic d3Jvbmc6dXNlcg==
Response:
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Authorization Required"
Unauthorized
Access Dashboard With Valid Credentials
- Base64-encoded of ram:123 is cmFtOjEyMw==
Request:
GET: http://localhost:5000/dashboard
Authorization: Basic cmFtOjEyMw==
Response:
Status: 200 OK
Content-Type: application/json
{
"message": "Welcome to Dashboard Page!"
}