H
H
heducose2017-07-21 20:29:46
JSON Web Token
heducose, 2017-07-21 20:29:46

How to validate against a specific payload value in express-jwt?

Hello. I'm trying to replace passport-jwt with express-jwt and I can't figure out how to use it from their documentation?
This is the code I have on my Passport

const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('authorization'),
  secretOrKey: process.env.SECRET
}

const jwtLogin = new JwtStrategy(jwtOptions, function (payload, done) {
  User.findById(payload.sub, function (err, user) {
    if (err) { return done (err, false) }
    if (user) {
      done (null, user)
    } else {
      done (null, false)
    }
  })
})

Actually the route itself
const requireAuth = passport.authenticate('jwt', { session: false })

router.get('/demo', requireAuth, function (req, res) {
   res.send({hi: 'SECRET test authorization of registered user'})
})

The problem is that I can't figure out how to perform express-jwt validation against sub value?
router.get('/demo', jwt({ secret: process.env.SECRET }), function (req, res) {
  res.send({hi: 'SECRET test authorization of registered user'})
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kuznetsov, 2017-07-22
@heducose

var jwt = require('express-jwt');

app.get('/protected',
  jwt({secret: 'shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);
  });

If I understand correctly, jwt({secret: 'shhhhhhared-secret'}),it tells us that when accessing, '/protect'we need to use the jwt middleware with settings {secret: 'shhhhhhared-secret'}and decrypt the HMAC token using the secret phrase 'shhhhhhared-secret', then shove the resulting account into the request.
inside the same
function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
you get req and user, and check already access based on account data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question