0
votes

I'm using Passport with the passport-jwt strategy to authenticate users with a JavaScript Work Token. I need to be able to authorise users based on some metadata so I've set up a custom callback which I'm attaching to the route.

router.get('/', auth.loginRequired, function (req, res) {...

but I'm having problems calling the function. I've massively simplified it and the strategy as shown below:

module.exports = {
  loginRequired: function (req, res, next) {
    passport.authenticate('jwt', {session: false}, function(err, user, info) {
      if (!err) {
        next()
      } else {
        res.status(401).send
      }
    })(req, res, next)
  }
}

The strategy is shown below:

passport.use(new JwtStrategy(opts, function(payload, done) {
  var user = {firstName: 'Geraint', email: '[email protected]'}
  if (payload) {
    done(null, user)
  } else {
    done('Error', null)
  }
}))

When the JWT is valid, the passport.authenticate callback is being called as expected with null and the user being passed in correctly. When the JWT is invalid though, the error is being passed into the authenticate callback as info. err is null and user is false.

Why are the parameters getting jumbled if there's an error?

2

2 Answers

0
votes

What I do for JWT authentication is:

router.get('/', passport.authenticate('jwt', {session: false}), function (req, res) {...

If the JWT is not valid, then it returns a 401. If it is valid, then it continues into my route.

0
votes

I also worked with this and i got the same output. Passport js work in this way only.

You can change condition and it will work

module.exports = {
  loginRequired: function (req, res, next) {
    passport.authenticate('jwt', {session: false}, function(err, user, info) {
      if (user) {
        next()
      } else {
        res.status(401).send
      }
    })(req, res, next)
  }
}

In case of user object present, it will return success otherwise it will return error.