Passport HTTP Bearer Strategy

1.0.1 · maintenance · verified Tue Apr 21

The `passport-http-bearer` module provides an authentication strategy for Passport.js, specifically designed to handle HTTP Bearer tokens as defined by RFC 6750. This module allows Node.js applications, particularly those using Connect-style middleware like Express, to easily integrate token-based authentication for API endpoints. Bearer tokens are a common mechanism for securing REST APIs and are frequently issued in conjunction with OAuth 2.0. The current stable version is 1.0.1, last published in 2013, indicating a mature and stable codebase with a very low release cadence, focusing on reliability rather than frequent feature additions. It differentiates itself by providing a robust, battle-tested solution for a core authentication pattern within the Passport.js framework, leveraging its pluggable middleware architecture. TypeScript definitions are available via `@types/passport-http-bearer` for enhanced developer experience.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `passport-http-bearer` with Express and Passport to protect an API endpoint using a static bearer token. It includes a simple in-memory user store for token verification.

import express from 'express';
import passport from 'passport';
import { Strategy as BearerStrategy } from 'passport-http-bearer';

const app = express();
const PORT = process.env.PORT || 3000;

// Dummy User/Token database for example purposes
const users = [
  { id: '1', username: 'testuser', token: 'a1b2c3d4e5f6' },
];

// Configure the Bearer strategy
passport.use(new BearerStrategy(
  async (token, done) => {
    console.log(`Attempting to verify token: ${token}`);
    try {
      const user = users.find(u => u.token === token);
      if (!user) {
        console.log('Invalid token provided.');
        return done(null, false, { message: 'Invalid token' });
      }
      console.log(`Token verified for user: ${user.username}`);
      return done(null, user, { scope: 'all' });
    } catch (err) {
      console.error('Error during token verification:', err);
      return done(err);
    }
  }
));

// Initialize Passport
app.use(passport.initialize());

// Protected route using bearer authentication
app.get('/api/protected', 
  passport.authenticate('bearer', { session: false }),
  (req, res) => {
    // If authentication successful, req.user will be populated
    const user = req.user as typeof users[0] | undefined;
    if (user) {
      res.json({ message: `Hello, ${user.username}! You have access to protected data.` });
    } else {
      res.status(401).json({ message: 'Authentication required.' });
    }
  }
);

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Test with: curl -H "Authorization: Bearer a1b2c3d4e5f6" http://localhost:3000/api/protected');
  console.log('Test with invalid token: curl -H "Authorization: Bearer wrongtoken" http://localhost:3000/api/protected');
});

view raw JSON →