Shamoon
Shamoon

Reputation: 43491

How to authenticate a route with passport-jwt?

I'm using passport-jwt and my strategy is setup like:

  let jwtOptions = {}
  jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
  jwtOptions.secretOrKey = process.env.SECRET

  var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
    console.log('payload received', jwt_payload);
    // usually this would be a database call:
    var user = users[_.findIndex(users, { id: jwt_payload.id })];
    if (user) {
      next(null, user);
    } else {
      next(null, false);
    }
  })
  passport.use(strategy)

So when I POST to a /login route, I'm able to generate a token:

  var payload = { id: user.id }
  var token = jwt.sign(payload, jwtOptions.secretOrKey)
  res.json({ message: "ok", token: token })

But then when I try to have a route that requires a token:

  app.get("/secret", passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json("Success! You can not see this without a token");
  })

My header has Authorization: JWT [token]

it continually returns a 401. What am I doing wrong?

Upvotes: 3

Views: 1798

Answers (2)

masoud parpanchi
masoud parpanchi

Reputation: 126

if you are sending token in header and using your own scheme (in your case you are using "JWT" ) you can use fromAuthHeaderWithScheme(auth_scheme) method.

you can find more detail in passport-jwt docs :

  • fromAuthHeaderWithScheme(auth_scheme) creates a new extractor that looks for the JWT in the authorization header, expecting the scheme to match auth_scheme.
  • fromAuthHeaderAsBearerToken() creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'

https://www.npmjs.com/package/passport-jwt

Upvotes: 2

Paul
Paul

Reputation: 36319

Your authorization header is incorrectly formatted. Per the jwt-strategy docs

fromAuthHeaderAsBearerToken() creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'

So your header should be Authorization: Bearer [token]

Upvotes: 3

Related Questions