HTTP Basic and Digest Authentication for Node.js

4.2.1 · active · verified Tue Apr 21

The `http-auth` package provides robust HTTP basic and digest access authentication capabilities for Node.js applications. Currently stable at version 4.2.1, it receives infrequent but consistent updates, addressing security and dependency concerns (e.g., uuid updates, security fixes in 4.1.3). It differentiates itself by offering built-in support for both basic and digest authentication schemes, configurable realms, and flexible user credential storage, including file-based methods (e.g., `.htpasswd` format). While primarily designed for CommonJS environments, it offers a straightforward API for integrating authentication into standard Node.js HTTP servers, allowing developers to define custom user stores via file paths or callback functions, and customize authentication parameters like algorithm (MD5, MD5-sess) and Quality of Protection (QOP) for digest authentication.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic HTTP server with HTTP Basic Authentication, reading user credentials from a temporary `.htpasswd` file. It demonstrates how to initialize the `basic` authentication middleware and integrate it into a standard Node.js `http.createServer` callback.

const http = require("http");
const auth = require("http-auth");
const path = require('path');
const fs = require('fs');

// Create a dummy .htpasswd file for the example
const htpasswdPath = path.join(__dirname, "users.htpasswd");
fs.writeFileSync(htpasswdPath, "gevorg:gpass\nSarah:testpass");

const basicAuth = auth.basic({
  realm: "Protected Area.",
  file: htpasswdPath // gevorg:gpass, Sarah:testpass
});

http.createServer(
  basicAuth.check((req, res) => {
    res.end(`Welcome to the private area - ${req.user} (${req.method} ${req.url})!`);
  })
)
.listen(1337, () => {
  console.log("Server running at http://127.0.0.1:1337/");
  console.log("Try accessing with 'gevorg' and 'gpass' or 'Sarah' and 'testpass'.");
  console.log("To stop the server, press Ctrl+C. The users.htpasswd file will be removed.");
});

// Clean up the dummy file on exit
process.on('exit', () => {
  if (fs.existsSync(htpasswdPath)) {
    fs.unlinkSync(htpasswdPath);
    console.log("Cleaned up users.htpasswd");
  }
});

view raw JSON →