{"id":16173,"library":"passport-http-bearer","title":"Passport HTTP Bearer Strategy","description":"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.","status":"maintenance","version":"1.0.1","language":"javascript","source_language":"en","source_url":"git://github.com/jaredhanson/passport-http-bearer","tags":["javascript","passport","auth","authn","authentication","authz","authorization","http","bearer"],"install":[{"cmd":"npm install passport-http-bearer","lang":"bash","label":"npm"},{"cmd":"yarn add passport-http-bearer","lang":"bash","label":"yarn"},{"cmd":"pnpm add passport-http-bearer","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core authentication middleware that this strategy plugs into.","package":"passport","optional":false},{"reason":"Provides TypeScript type definitions for the strategy.","package":"@types/passport-http-bearer","optional":true},{"reason":"Provides TypeScript type definitions for the core Passport library.","package":"@types/passport","optional":true},{"reason":"Provides TypeScript type definitions for Express.js, commonly used with Passport strategies.","package":"@types/express","optional":true}],"imports":[{"note":"While CommonJS `require` is still widely used, modern Node.js projects often prefer ESM `import`. The default export is the `Strategy` class itself, hence the alias.","wrong":"const BearerStrategy = require('passport-http-bearer').Strategy;","symbol":"Strategy","correct":"import { Strategy as BearerStrategy } from 'passport-http-bearer';"},{"note":"This is the traditional and fully supported CommonJS import pattern.","symbol":"BearerStrategy (CommonJS)","correct":"const BearerStrategy = require('passport-http-bearer').Strategy;"},{"note":"When using TypeScript, importing the `Strategy` class directly and its `VerifyFunction` types helps define the callback signature correctly, especially for `passReqToCallback` scenarios.","symbol":"BearerStrategy (Type Import)","correct":"import { Strategy as BearerStrategy } from 'passport-http-bearer';\nimport { VerifyFunction, VerifyFunctionWithRequest } from 'passport-http-bearer';"}],"quickstart":{"code":"import express from 'express';\nimport passport from 'passport';\nimport { Strategy as BearerStrategy } from 'passport-http-bearer';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Dummy User/Token database for example purposes\nconst users = [\n  { id: '1', username: 'testuser', token: 'a1b2c3d4e5f6' },\n];\n\n// Configure the Bearer strategy\npassport.use(new BearerStrategy(\n  async (token, done) => {\n    console.log(`Attempting to verify token: ${token}`);\n    try {\n      const user = users.find(u => u.token === token);\n      if (!user) {\n        console.log('Invalid token provided.');\n        return done(null, false, { message: 'Invalid token' });\n      }\n      console.log(`Token verified for user: ${user.username}`);\n      return done(null, user, { scope: 'all' });\n    } catch (err) {\n      console.error('Error during token verification:', err);\n      return done(err);\n    }\n  }\n));\n\n// Initialize Passport\napp.use(passport.initialize());\n\n// Protected route using bearer authentication\napp.get('/api/protected', \n  passport.authenticate('bearer', { session: false }),\n  (req, res) => {\n    // If authentication successful, req.user will be populated\n    const user = req.user as typeof users[0] | undefined;\n    if (user) {\n      res.json({ message: `Hello, ${user.username}! You have access to protected data.` });\n    } else {\n      res.status(401).json({ message: 'Authentication required.' });\n    }\n  }\n);\n\n// Start the server\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Test with: curl -H \"Authorization: Bearer a1b2c3d4e5f6\" http://localhost:3000/api/protected');\n  console.log('Test with invalid token: curl -H \"Authorization: Bearer wrongtoken\" http://localhost:3000/api/protected');\n});\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure your application always uses HTTPS/TLS. Implement secure storage practices for tokens if they are persistent (e.g., client-side storage, secure databases).","message":"Bearer tokens are credentials that grant access to resources to anyone who possesses them. They must be protected from disclosure both in storage and during transport (e.g., always use HTTPS). Treat them with the same security considerations as passwords.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always include `{ session: false }` in the options object for `passport.authenticate('bearer', { session: false })` when authenticating API requests.","message":"When using `passport.authenticate('bearer')` for API routes, it is generally recommended to set `session: false`. Bearer token authentication is typically stateless, and not using sessions reduces overhead and potential attack vectors related to session management.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If your verify callback expects `(req, token, done)`, you *must* initialize the strategy with `new BearerStrategy({ passReqToCallback: true }, verifyCallback)`. If it expects `(token, done)`, ensure `passReqToCallback` is `false` (default) or omitted.","message":"The `BearerStrategy`'s `verify` callback can optionally receive the `req` object as its first argument by setting `passReqToCallback: true` in the strategy options. Forgetting this option or mismatching the callback signature can lead to unexpected behavior or `undefined` values.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Install `@types/passport-http-bearer` and `@types/passport`. Explicitly import `VerifyFunction` or `VerifyFunctionWithRequest` from `passport-http-bearer` to correctly type your callback parameters (e.g., `async (token: string, done: VerifyCallback) => { ... }` or `async (req: Request, token: string, done: VerifyCallback) => { ... }`).","message":"In TypeScript, incorrect type definitions for the `verify` callback can lead to implicit `any` errors or type mismatches, especially when `passReqToCallback` is involved.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure the `BearerStrategy` constructor receives a valid function as its second argument (or first, if no options object is provided). Example: `new BearerStrategy(function(token, done) { /* ... */ })`.","cause":"The `BearerStrategy` was initialized without a callback function to verify the token, or the callback was not a function.","error":"TypeError: HTTPBearerStrategy requires a verify callback"},{"fix":"Verify the client is sending the token correctly in the `Authorization: Bearer <token>` header or as `access_token` in query/body. Debug the `verify` callback to ensure it correctly finds and validates the token against your user/token store. Custom error messages can be returned via `done(null, false, { message: 'Custom message' })`.","cause":"The bearer token provided in the request was invalid, missing, or the `verify` callback returned `done(null, false)` indicating authentication failure. Passport's default behavior for failing authentication is to send a 401.","error":"HTTP 401 Unauthorized / { \"message\": \"Unauthorized\" } (or similar)"},{"fix":"Ensure `passport.authenticate('bearer', { session: false })` is correctly placed as middleware in your route. If you are handling authentication outcome manually, ensure `passport.authenticate('bearer', function(err, user, info) { /* ... */ })(req, res, next)` uses a valid callback and immediately invokes it with `(req, res, next)`.","cause":"This error typically indicates that `passport.authenticate('bearer')` was called without a valid callback or that the middleware chain was incorrectly configured, preventing Passport from handling the request properly.","error":"Error: bearer.authenticate() requires a callback function (or similar Passport internal error)"}],"ecosystem":"npm"}