With Passport and passport-jwt in an Express API, how do you protect a route with a bearer token from the Authorization header?
answer
- a strategy registered once
- where the token is read from
- bearer-scheme extractor factory
- secret or public key plus verify
- no login session on the route
basics
~10 sRegister a passport-jwt JwtStrategy with jwtFromRequest set to ExtractJwt.fromAuthHeaderAsBearerToken() and a secretOrKey, map the verified payload to a user in its verify callback, then guard routes with passport.authenticate('jwt', { session: false }).
solid answer
~40 sI register `new JwtStrategy(options, verify)` with `passport.use`. The options say where the token comes from, `jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()`, which reads `Authorization: Bearer <token>` with the scheme matched case-insensitively, and how to check it: `secretOrKey` (a shared secret or a PEM public key) or `secretOrKeyProvider`, plus `issuer`, `audience` and `algorithms` to pin. The strategy verifies the token before my `verify(payload, done)` runs, so the callback only maps `payload.sub` to a user and calls `done(null, user)` or `done(null, false)`. The route gets `passport.authenticate('jwt', { session: false })`: a missing, bad or expired token, or `done(null, false)`, ends in a plain 401, and on success `req.user` holds the user for that request only.
code
javascript · 21 linesconst express = require('express');
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
async function findUserById(id) {
// look the user up in your data layer; resolve undefined when absent
}
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
algorithms: ['HS256'],
}, (payload, done) => {
findUserById(payload.sub).then((user) => done(null, user || false), done);
}));
const app = express();
app.get('/api/profile',
passport.authenticate('jwt', { session: false }),
(req, res) => res.json({ id: req.user.id }));go deeper
Recall the three pieces: JwtStrategy with jwtFromRequest and secretOrKey, a verify callback that maps the payload to a user, and passport.authenticate('jwt', { session: false }) on the route.
Explain the order: extract, verify signature and expiry, only then the verify callback. Know which outcomes become a 401 and which reach error middleware.
Show you would pin algorithms, issuer and audience, keep the token out of URLs, use failWithError for a consistent error body, and guard a whole router so no route forgets the option.
Frame the trade-off: per-request token checks keep the API stateless and horizontally simple, but revocation and key rotation now live with the token issuer, so ask who owns those.
## What passport-jwt adds to Passport **Passport** is authentication middleware for Express that delegates each way of signing in to a **strategy**. **passport-jwt** is the strategy for a **JSON Web Token** (JWT) that the client sends with every request. Its README describes it as intended for securing RESTful endpoints **without sessions**: the client presents the token each time, and the server keeps no login state between requests. You build it with `new JwtStrategy(options, verify)` and register it with `passport.use()`. It registers itself under the name `'jwt'`, which is the name `passport.authenticate()` takes. ## The options that matter | Option | What it does | |---|---| | `jwtFromRequest` | Required. A function that takes the request and returns the raw token string or `null` | | `secretOrKey` | A shared secret or a PEM-encoded public key used to check the signature | | `secretOrKeyProvider` | A callback `(request, rawJwtToken, done)` that supplies the key per request; use it instead of `secretOrKey`, never together | | `issuer`, `audience`, `algorithms` | Passed to the verifier, which then checks the token's `iss` and `aud` and accepts only the listed algorithms | | `passReqToCallback` | When `true`, the verify callback receives `(req, payload, done)` | The constructor throws a `TypeError` when the key or `jwtFromRequest` is missing, so a misconfigured strategy fails when the app boots rather than on the first request. `ExtractJwt.fromAuthHeaderAsBearerToken()` reads the `Authorization` header and returns its value only when the scheme is `bearer`, compared case-insensitively, so `Bearer abc` and `bearer abc` both work. A header with another scheme, such as `JWT abc`, yields no token. The other factories on `ExtractJwt` are `fromHeader(name)`, `fromBodyField(name)`, `fromUrlQueryParameter(name)`, `fromAuthHeaderWithScheme(scheme)` and `fromExtractors([...])`, which tries several extractors in order. ## What happens on each request 1. `passport.authenticate('jwt', { session: false })` runs the strategy. 2. The extractor pulls the token out of the request. No token means the attempt fails. 3. The strategy obtains the key and verifies the token's signature and claims, including expiry. Any failure here, such as a wrong signature, an expired token or a wrong issuer, fails the attempt. 4. Only then does your **verify callback** run, with the decoded payload. It looks the user up, typically from `payload.sub`, and calls `done`. 5. On success Passport sets `req.user` and calls `next()`, so the route handler runs. ## Outcomes and what the client sees | Situation | Result | |---|---| | Header missing, wrong scheme, bad signature, expired token | 401 with the body `Unauthorized`; the verify callback never runs | | `done(null, false)`, no such user | 401 with the body `Unauthorized` | | `done(err)`, the lookup itself failed | the error goes to error middleware through `next(err)` | | `done(null, user)` | `req.user` is set and the handler runs | passport-jwt reports its failures with an error object rather than a challenge string, so Passport sets no `WWW-Authenticate` header on these 401 responses. To answer in your API's own error format, add `failWithError: true`: Passport then hands an `AuthenticationError` whose `status` is 401 to your error middleware instead of ending the response itself. ## Why `{ session: false }` belongs on the route `passport.authenticate()` defaults its `session` option to `true`. On success it would then call `req.login()` to store the user in a server-side session, which an API that receives a token on every call does not want, and which fails outright when no session middleware is mounted. With `session: false`, `req.user` lives for the current request only, and the next request has to bring its token again. ## Common mistakes - Decoding or verifying the token again inside the verify callback: the strategy has already done both before the callback runs. - Leaving `{ session: false }` off an API route. - Not pinning `algorithms`, `issuer` and `audience` when you know who issues the tokens; what each claim check defends against is covered with JWT validation. - Reading the token from the query string for convenience: URLs end up in access logs and browser history.
- What does the client receive when the token is missing or expired, and how do you return your own error body instead?A 401 whose body is the plain word `Unauthorized`, with no `WWW-Authenticate` header, because passport-jwt fails with an error object rather than a challenge string. Add `failWithError: true` to `passport.authenticate()` and Passport passes an `AuthenticationError` with `status` 401 to error middleware, which can then render the API's usual error JSON.
- During a client migration some requests carry the token in a custom header instead; how do you accept both?Combine extractors with `ExtractJwt.fromExtractors([ExtractJwt.fromAuthHeaderAsBearerToken(), ExtractJwt.fromHeader('x-access-token')])`; they are tried in order until one returns a token. Name the header in lower case, because Node exposes incoming header names lower-cased, and note that `fromHeader` returns the whole header value, so that header must carry the bare token.
- Why would you use secretOrKeyProvider instead of secretOrKey?When the key is not one fixed value: the issuer signs with rotating asymmetric keys, or different tenants use different keys. `secretOrKeyProvider(request, rawJwtToken, done)` runs per request and calls `done(null, key)`; decoding the token's header to pick the key is up to you. Passing both options makes the constructor throw.
- The verify callback must decode the token and check its signature itself.
- passport-jwt turns sessions off by itself because tokens are stateless.
- fromAuthHeaderAsBearerToken also finds the token in cookies or the query string.
- Calling done(null, false) in the verify callback produces a 500 error.
- The strategy is registered under the name 'bearer'.