Passport.js Strategy for HTTP Basic/Digest Authentication via http-auth
http-auth-passport provides an integration layer that allows the use of the `http-auth` module's HTTP Basic and Digest access authentication within the Passport.js framework. This package enables developers to easily implement traditional HTTP authentication schemes in their Node.js applications, particularly those built with Express.js, leveraging Passport's robust strategy pattern. The current stable version is 1.0.7, with its last known release in 2021. The package itself has received minimal updates since then, indicating a slow maintenance cadence primarily focused on critical bug fixes or essential dependency alignments rather than active feature development. It serves a niche by bridging `http-auth`'s specific capabilities with the broader Passport ecosystem, offering an alternative to direct implementations like `passport-http` when `http-auth`'s features are preferred.
Common errors
-
TypeError: auth.basic is not a function
cause The `http-auth` module was either not installed, installed incorrectly, or an incompatible version is in use that does not expose the `basic` method directly on its default export.fixEnsure `http-auth` is correctly installed via `npm install http-auth`. Verify your import statement is `const auth = require('http-auth');`. If the issue persists, check `http-auth`'s documentation for any breaking changes in its API. -
Error: Unknown authentication strategy "http"
cause The `http-auth-passport` strategy, which is identified as 'http', was not successfully registered with the Passport.js middleware before being used in a route.fixConfirm that `passport.use(authPassport(basic));` is executed prior to any route that calls `passport.authenticate('http', ...)`. Ensure `authPassport` is correctly imported from `http-auth-passport` and that the `basic` instance is properly configured. -
401 Unauthorized Response
cause The server responded with 401 Unauthorized, indicating that the provided credentials (or lack thereof) were insufficient or incorrect for the protected resource.fixCheck the username and password being sent in the `Authorization` header. Verify that the `.htpasswd` file's content or the custom credential callback's logic matches the expected values. Ensure the client (e.g., browser or API tool) is correctly sending the HTTP Basic Authorization header with each request.
Warnings
- breaking This package is primarily a CommonJS module. Direct usage in a purely ESM Node.js environment (`"type": "module"` in package.json) might lead to `require is not defined` errors or require specific interoperability configurations or bundler setups.
- gotcha The package `http-auth-passport` has not seen significant feature development or updates since its last release in 2021. It might not be fully compatible with major version updates of `passport` (e.g., v0.6.0+ which introduced asynchronous `req.login()`/`req.logout()` and changes in middleware extending request objects) without explicit testing.
- gotcha The example and typical use case for `http-auth-passport` explicitly disable sessions using `session: false` in `passport.authenticate()`. This is appropriate for stateless API authentication but will prevent session-based persistent logins for web applications.
- gotcha HTTP Basic authentication transmits credentials (username and password) in Base64-encoded plain text over the network. Without HTTPS, these credentials can be easily intercepted and compromised by attackers.
- deprecated The underlying `http-auth` module, which `http-auth-passport` integrates with, has been reported with an 'Inactive' maintenance status by security tools like Snyk, despite some recent NPM publishes. This indicates potentially slow responses to new feature requests, bug reports, or security vulnerabilities in the core authentication logic.
- gotcha When configuring `auth.basic()` or `auth.digest()`, providing a correct and accessible path to the `.htpasswd` or `.htdigest` file, or ensuring the callback returns credentials in the expected format, is crucial. Incorrect paths or malformed files/callbacks will result in authentication failures.
Install
-
npm install http-auth-passport -
yarn add http-auth-passport -
pnpm add http-auth-passport
Imports
- authPassport
import { authPassport } from 'http-auth-passport';const authPassport = require('http-auth-passport'); - auth
import { auth } from 'http-auth';const auth = require('http-auth'); - passport
import { passport } from 'passport';const passport = require('passport');
Quickstart
const express = require('express');
const auth = require('http-auth');
const authPassport = require('http-auth-passport');
const passport = require('passport');
const fs = require('fs');
// Create a dummy .htpasswd file for demonstration
const htpasswdContent = 'testuser:testpass\nadmin:securepass';
const htpasswdPath = `${__dirname}/users.htpasswd`;
fs.writeFileSync(htpasswdPath, htpasswdContent);
const basic = auth.basic({
realm: 'Secure Area',
file: htpasswdPath // Path to your .htpasswd file
});
passport.use(authPassport(basic));
const app = express();
app.get('/', passport.authenticate('http', { session: false }), (req, res) => {
res.end(`Welcome, ${req.user}! You are authenticated with HTTP Basic.`);
});
app.listen(1337, () => {
console.log('Server running at http://127.0.0.1:1337/');
console.log('Try accessing http://127.0.0.1:1337/ with username: testuser, password: testpass');
console.log('Or with username: admin, password: securepass');
});