HTTP Authorization Header Parser and Formatter

1.0.0 · maintenance · verified Wed Apr 22

The `auth-header` library provides a robust solution for parsing and formatting HTTP `Authorization` and `WWW-Authenticate` headers. It supports various authentication schemes, including Basic, Digest, AWS, and Bearer/OAuth, adhering primarily to RFC7235 while also accommodating certain legacy formats by being less strict in its parsing. Currently at version 1.0.0, the library offers a stable API, though it appears to be in a maintenance state with no new feature development or active bug fixes since 2017. Its core differentiator lies in abstracting the complexities of these historically inconsistent HTTP headers, offering a standardized programmatic interface for their manipulation, which is a significant improvement over manual string parsing.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `auth-header` within an Express application to parse an incoming `Authorization` header and format a `WWW-Authenticate` header for basic authentication. It checks for a 'Basic' scheme, decodes the credentials, and performs a simple password verification.

import * as authorization from 'auth-header';
import express from 'express';

const app = express();

app.get('/', function(req, res) {

	// Helper function for authentication failure
	function fail() {
		res.set('WWW-Authenticate', authorization.format('Basic'));
		res.status(401).send();
	}

	// Get authorization header from request
	const authHeader = req.get('authorization');

	// If no header, fail immediately
	if (!authHeader) {
		return fail();
	}

	// Parse the authorization header
	const auth = authorization.parse(authHeader);

	// No basic authentication provided or wrong scheme
	if (!auth || auth.scheme !== 'Basic') {
		return fail();
	}

	// Get the basic auth component (username:password)
	// Using Buffer for base64 decoding, which is Node.js specific.
	let [un, pw] = ['', ''];
	if (auth.token) {
		[un, pw] = Buffer.from(auth.token, 'base64').toString('utf8').split(':', 2);
	}

	// Verify authentication (simple hardcoded example)
	if (pw !== 'admin') {
		return fail();
	}

	// Authentication successful
	res.send('Hello world.');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

view raw JSON →