HTTP Authorization Header Parser and Formatter
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
-
TypeError: Cannot read properties of undefined (reading 'scheme')
cause The `authorization.parse()` method returned `undefined` because the input header string was null, undefined, empty, or completely unparseable, and subsequent code attempted to access properties of the `undefined` result.fixAlways check if the result of `authorization.parse()` is a valid object before attempting to access its properties. For example: `const auth = authorization.parse(headerValue); if (!auth) { /* handle unparseable header */ }` -
TypeError: authorization.parse is not a function
cause This typically occurs when attempting to use a CommonJS `require()` pattern (`const authorization = require('auth-header');`) for a module primarily designed for ES module `import` syntax, or vice-versa, or when incorrectly trying to destructure named exports (`import { parse } from 'auth-header';`) instead of using the namespace import.fixEnsure you are using the correct import pattern: `import * as authorization from 'auth-header';` and then access `authorization.parse()` and `authorization.format()`. -
ReferenceError: Buffer is not defined
cause The `Buffer` global object, commonly used for base64 encoding/decoding in Node.js, is not available in browser environments or other JavaScript runtimes.fixIf running in a browser, use `atob(auth.token)` for base64 decoding. If targeting universal environments, consider a polyfill or a library like `js-base64` for encoding/decoding operations.
Warnings
- gotcha The library explicitly only supports `WWW-Authenticate` headers where multiple authentication challenges appear in multiple distinct headers, not when they are concatenated into a single header. Attempting to parse a single `WWW-Authenticate` header with multiple challenges may lead to incomplete or incorrect results.
- gotcha While adhering to RFC7235, the library is intentionally 'less strict' than it could be to parse some legacy authorization header formats. This leniency might allow parsing of malformed headers that a stricter parser would reject.
- gotcha The `auth-header` project appears to be in a maintenance or abandoned state. The last significant commit was in February 2017, meaning no new features, active bug fixes, or security updates are to be expected. While stable, consider this for long-term project viability.
- gotcha The `quickstart` example and common use cases involving basic authentication often require base64 decoding (e.g., `Buffer.from(auth.token, 'base64').toString()`). `Buffer` is a Node.js global object. If using this library in a browser environment or a runtime without `Buffer`, you will encounter a `ReferenceError`.
Install
-
npm install auth-header -
yarn add auth-header -
pnpm add auth-header
Imports
- authorization
const authorization = require('auth-header');import * as authorization from 'auth-header';
- authorization.parse
import { parse } from 'auth-header';const parsedHeader = authorization.parse(req.get('authorization')); - authorization.format
import { format } from 'auth-header';res.set('WWW-Authenticate', authorization.format('Basic'));
Quickstart
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');
});