Basic Authentication Example

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.

How It Works

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.

Server-Side Implementation (Conceptual)

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.

Conceptual Server Logic (Node.js Example)


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');
});
                
Security Note: Basic authentication sends credentials encoded in Base64, which is easily decoded. It is not recommended for sensitive information over unencrypted HTTP. For secure communication, always use HTTPS. For more robust authentication, consider token-based methods like OAuth or JWT.

Client-Side Behavior

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.

Example Scenario

  1. You try to access a URL that requires authentication.
  2. Your browser receives a 401 Unauthorized response.
  3. The browser displays a login prompt.
  4. You enter your username and password.
  5. Your browser sends a new request with the encoded credentials in the Authorization header.
  6. The server validates the credentials and, if correct, serves the requested content.

This example provides a foundational understanding of basic HTTP authentication. For production environments, it's crucial to implement more secure authentication and authorization strategies.