{"id":17866,"library":"passport-http-header-strategy","title":"Passport HTTP Header Authentication Strategy","description":"The `passport-http-header-strategy` package provides a flexible HTTP header-based authentication strategy for the Passport.js framework. It enables developers to authenticate requests by extracting a token from a custom HTTP header (e.g., `X-API-Key`), or optionally from a request body or query parameter, rather than being limited to the standard `Authorization: Bearer` scheme. Currently at version 1.1.0, the package has not seen significant updates in several years, suggesting a stable but largely unmaintained status. It integrates seamlessly into existing Passport-based applications, allowing for stateless (session-less) authentication, which is common for API-driven services. Its key differentiator is the configurability of the header name and parameter name, offering more customization than some other token-based strategies.","status":"maintenance","version":"1.1.0","language":"javascript","source_language":"en","source_url":"git://github.com/FengYuHe/passport-http-header-strategy","tags":["javascript","passport","header","auth","authn","authentication","authz","authorization","http","typescript"],"install":[{"cmd":"npm install passport-http-header-strategy","lang":"bash","label":"npm"},{"cmd":"yarn add passport-http-header-strategy","lang":"bash","label":"yarn"},{"cmd":"pnpm add passport-http-header-strategy","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core peer dependency for Passport.js authentication framework.","package":"passport","optional":false}],"imports":[{"note":"The class for the strategy is typically exported as `Strategy`.","wrong":"const Strategy = require('passport-http-header-strategy');","symbol":"Strategy","correct":"import { Strategy } from 'passport-http-header-strategy';"},{"note":"Passport.js itself is usually imported as a default export.","wrong":"import { Passport } from 'passport';","symbol":"Passport","correct":"import passport from 'passport';"},{"note":"This type definition illustrates the expected signature for the strategy's verify callback when `passReqToCallback` is `true`.","symbol":"VerifyCallback","correct":"type VerifyCallback = (req: Request, token: string, done: (error: any, user?: any, info?: any) => void) => void;"}],"quickstart":{"code":"import express from 'express';\nimport passport from 'passport';\nimport { Strategy } from 'passport-http-header-strategy';\n\nconst app = express();\napp.use(express.json()); // For parsing req.body if 'param' option is used\n\n// Mock user database for demonstration\nconst users = [\n  { id: 1, username: 'testuser', token: 'mysecrettoken123' },\n  { id: 2, username: 'admin', token: 'adminsecuretoken' }\n];\n\n// Configure the HTTP Header Strategy\npassport.use('header-token', new Strategy({\n    header: 'X-APP-TOKEN',          // Name of the header to check for the token\n    param: 'app_token',            // Optional: Name of param in req.body/req.query if header isn't found\n    passReqToCallback: true        // Pass the request object to the verify callback\n  },\n  function(req, token, done) {\n    console.log(`Attempting authentication with token: ${token} from header: ${req.headers['x-app-token']}`);\n\n    const user = users.find(u => u.token === token);\n\n    if (!user) {\n      return done(null, false, { message: 'Invalid token provided.' });\n    }\n    // In a real application, perform secure token validation (e.g., database lookup, JWT verification)\n    return done(null, user, { scope: 'all' });\n  }\n));\n\n// Protected route using the 'header-token' strategy\napp.get('/protected', \n  passport.authenticate('header-token', { session: false }),\n  function(req, res) {\n    res.json({ \n      message: `Hello, ${req.user.username}! This is a protected resource.`, \n      user: req.user \n    });\n  }\n);\n\n// Unprotected root route\napp.get('/', (req, res) => {\n    res.send('Welcome. Try GET /protected with an X-APP-TOKEN header.');\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Test with cURL:');\n  console.log(`curl -H \"X-APP-TOKEN: mysecrettoken123\" http://localhost:${PORT}/protected`);\n  console.log(`curl http://localhost:${PORT}/protected`); // Should result in 401 Unauthorized\n});\n","lang":"typescript","description":"This quickstart demonstrates setting up an Express application with Passport.js and the `passport-http-header-strategy` to protect a route using a custom `X-APP-TOKEN` header. It includes a mock user database and instructions for testing via cURL."},"warnings":[{"fix":"Always include `{ session: false }` in the `passport.authenticate()` options for token strategies.","message":"It is critical to set `session: false` when using token-based authentication strategies like `passport-http-header-strategy`. This prevents Passport from attempting to create or use a session, which is unnecessary and potentially problematic for stateless API authentication.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your `verify` callback signature matches `(req, token, done)` if `passReqToCallback: true`, or `(token, done)` if `passReqToCallback: false`.","message":"The `passReqToCallback` option changes the signature of the `verify` callback. If set to `true`, the first argument to your callback will be the `req` object. Incorrectly matching the callback signature will lead to runtime errors or unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Thoroughly test with your target Node.js and Passport.js versions. Consider migrating to a more actively maintained strategy or implementing a custom strategy if advanced features or recent updates are critical.","message":"This package has not been updated in several years. While it may still function with recent Passport.js versions, there's a risk of incompatibility with newer Node.js releases, potential security vulnerabilities (though none specifically reported for this package), or lack of support for modern language features.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Implement proper token security measures: use strong cryptographic hashing (e.g., bcrypt) for API keys/static tokens, or verify JWTs using their signature and claims rather than simple database lookups.","message":"The example `User.findOne({ token: token })` from the README is insecure for production use. Raw tokens should never be stored directly in a database. Tokens should be hashed or, if JWTs, signed and verified without storing the full token.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure you call `passport.use('your-strategy-name', new Strategy(...))` and then use `passport.authenticate('your-strategy-name', ...)` with the exact same string name.","cause":"The Passport strategy has not been correctly registered or the name used in `passport.authenticate()` does not match the name provided to `passport.use()`.","error":"Unknown authentication strategy \"header\""},{"fix":"Provide a valid function as the second argument to `new Strategy(options, verifyCallback)`. This function is where you implement your token validation logic.","cause":"The second argument to the `Strategy` constructor (the function responsible for verifying the token) is missing or not a function.","error":"Strategy must be given a verify callback"},{"fix":"Ensure you have `app.use(passport.initialize());` (and optionally `app.use(passport.session());` if using sessions, though not recommended for this strategy) before any routes that use `passport.authenticate()`.","cause":"Passport middleware (`passport.initialize()`) is not configured or mounted correctly in your Express application, or `passport` is not properly imported.","error":"TypeError: Cannot read properties of undefined (reading 'authenticate')"},{"fix":"Carefully debug your `verify` callback. Ensure `done(null, user)` is called with a valid user object upon successful authentication. Check that the `header` or `param` options correctly match where your token is sent.","cause":"Your `verify` callback is incorrectly calling `done(null, false)` or `done(error)` even when the token is valid, or your token extraction logic is flawed.","error":"401 Unauthorized (when token is present and valid)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}