1

How to extract user id from jwt token? I am getting 'undefined' when I am trying to access 'id' property in 'decoded' object?

My code -

verifyToken: function(req, res, next) {
    var token = req.body.token || req.query.token || req.headers['access-token'];

    if (token) {

        jwt.verify(token, config.secret, function(err, decoded) {

            if (err) {
                return res.json({ success: false, message: 'Failed to authencticate token' });
            } else {

                // I want user id here. docoded.id is giving undefined

                req.user = decoded;
                next();
            }
        });
    } else {
        res.status(403).send({
            success: false,
            message: 'No token provided'
        });
    }
}
  • `console.log(decoded)` ? – Mukesh Sharma Sep 01 '17 at 08:34
  • 1
    You have to mention the exact npm package that you used and you have to show how did you sign your token as for example if I assume that you used `jsonwebtoken` and you signed you token like this `var jwt = require('jsonwebtoken'); var token = jwt.sign({ id: 'bar' }, config.secret);` the solution will be as simple as that `jwt.verify(token,config.secret, function(err, decoded) { console.log(decoded.id); });` – Karim Sep 01 '17 at 08:38
  • @Karim Thanks for the solution. I was specifying the user object w/o following key-value format in sign in function. – garvit vijai Sep 01 '17 at 08:58
  • Are you sure you have an `id` property? The user identifier use to be in `sub` property. It would be helpful if you post an axample token – pedrofb Sep 01 '17 at 12:11

0 Answers0