Get user id from jsonwebtoken in node with passport
The JWT claim that identifies the user presenting the JWT is sub
. If understand your code correctly, jwtPayload.sub
contains this claim.
If the value of the sub
claim contains what you call the user ID, you are done.
If you want to find the user based on a different value, maybe one derived from the sub
, you will have to tell us how this different value is related to the claims contained in the JWT.
While signing the JWT
(creating the new token), if you would add the user info in the jwt payload
something as below:
......const payload = { userId: user.id, email: user.email }; // CREATE A JWT TOKEN jwt.sign(payload, secretForJWT, { expiresIn: expirationTimeForJWT }, (err, token) => {......
Then you should be able to retrieve the userId
field from the decrypted token as below:
const jwtStrategy = new JwtStrategy(jwtOptions, (jwtPayload, done) => { console.log(jwtPayload); const userId = jwtPayload.userId; // YOU SHOULD GET THE USER ID FROM THE PAYLOAD User.findById(jwtPayload.sub, (err, user) => { if (err) return done(err, null); if (user) { return done(null, user) } else { return done(null, false) } })});exports.jwtOptions = jwtOptions;exports.jwt = jwtStrategy;
This is my way, hope it's helpful:
const jwt = require('jsonwebtoken');...const jwt_payload = jwt.decode(yourJwtInString);const id = jwt_payload._id;...