This document demonstrates a simple example of how to implement basic HTTP authentication in a web application. Basic authentication is a straightforward method for providing an identity for a user trying to access a protected resource.
When a client (like a web browser) requests a resource that requires authentication, the server responds with a 401 Unauthorized
status code and includes a WWW-Authenticate
header. This header specifies the authentication scheme, typically Basic
, and may include a realm.
The client then prompts the user for credentials (username and password). Upon receiving these, the client sends a new request for the same resource, this time including an Authorization
header in the format:
Authorization: Basic <credentials>
where <credentials>
is the base64 encoded string of username:password
.
A server-side script (e.g., in Node.js, Python, PHP) would typically intercept requests to protected routes. It checks for the presence and validity of the Authorization
header.
const express = require('express');
const app = express();
// Middleware to check for basic authentication
function requireAuth(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
res.setHeader('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Authentication required.');
}
const [authType, credentials] = authHeader.split(' ');
if (authType !== 'Basic') {
res.setHeader('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Invalid authentication type.');
}
try {
const [username, password] = Buffer.from(credentials, 'base64').toString().split(':');
// Replace with your actual username and password check
if (username === 'admin' && password === 'secret123') {
return next(); // User is authenticated
} else {
res.setHeader('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Invalid credentials.');
}
} catch (e) {
res.setHeader('WWW-Authenticate', 'Basic realm="Protected Area"');
return res.status(401).send('Malformed credentials.');
}
}
// Apply the authentication middleware to a specific route
app.get('/protected-resource', requireAuth, (req, res) => {
res.send('Welcome to the protected resource!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Most modern web browsers automatically handle the 401 Unauthorized
response by displaying a pop-up dialog for the user to enter their username and password. Once entered, the browser will include the necessary Authorization
header in subsequent requests to the same origin.
401 Unauthorized
response.Authorization
header.This example provides a foundational understanding of basic HTTP authentication. For production environments, it's crucial to implement more secure authentication and authorization strategies.