How to authenticate a route with passport-jwt?

219
December 06, 2017, at 03:08 AM

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?

Answer 1

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]

READ ALSO
Having an issue with order of operations in node.js function

Having an issue with order of operations in node.js function

I have a function that's I would like to use to poll historical data beginning from the start of Ethereum trading on the gdax exchange to currentI want the code to poll 100 results (max allowable at a time) insert results into mongodb, add 100, then repeat,...

172
Express/Mongoose use object function as callback doesn't work

Express/Mongoose use object function as callback doesn't work

I want to call function from my object in express routeThis function should call mongoose query, then run next, next etc

211
Mongoose validation failed, without giving the field-name with the issue

Mongoose validation failed, without giving the field-name with the issue

When I try to save my "Rating" schema, it gives the error

216
Should i create a new route or have a variable to decide what operation to do?

Should i create a new route or have a variable to decide what operation to do?

I am making a route for showing transactions to the users now for this, I have a route transactions but I am using this route for showing filtered transactions

169