How to get user.id from jwt token in Node.js?
Asked Answered
D

2

6

In my User controller, I create a token in which I save this user's id when he login to my application.

exports.findOne = (req, res) => {
  User.findOne({
    where: {
      login: req.body.login,
    },
  })
    .then(user => {
      if (user) {
        if (bcrypt.compareSync(req.body.password, user.password)) {
          const token = jwt.sign(
            {
              id: user.id, // this is the id I need.
            },
            env.SECRET_KEY,
            {
              expiresIn: 129600,
            },
          );
          return res.status(200).json({
            message: 'Auth successful',
            token,
          });
        }
       ...
      }
    })
    .catch(err => {
      res.status(400).json({ error: err });
    });
};

Now in another controller I would like to read this id and use it for my purpose. How can I get to it?

       const loginId = '?'; // here I want to give it to id
            Bill.update(
              {
                available_funds: available_funds - amountMoney,
              },
              { where: { id_owner: loginId } },
            ).then(() => {
              res.status(200).send(`ok`);
            });
Duralumin answered 22/12, 2018 at 16:43 Comment(1)
Possible duplicate of NodeJs - Retrieve user infor from JWT token?Crownwork
M
8

Make a middleware which checks the incoming token before forwarding to your update route. This middleware should be responsible for validating the incoming token which you pass from the client side code after logging in (storing token in cookies is commonly practiced).

Now in your middleware, you can do something similar to this:

app.use(function(req,res,next) {
 JWT.verify(req.cookies['token'], 'YOUR_SECRET', function(err, decodedToken) {
   if(err) { /* handle token err */ }
   else {
    req.userId = decodedToken.id;   // Add to req object
    next();
   }
 });
});

Then, finally in your upcoming controller, you can access the id from the request object:

   const loginId = req.userId;

    Bill.update(
      {
        available_funds: available_funds - amountMoney,
      },
      { where: { id_owner: loginId } },
    ).then(() => {
      res.status(200).send(`ok`);
    });
Melise answered 22/12, 2018 at 17:2 Comment(0)
C
0

JWT is an encrypted JSON. So, if you have the JWT and you have another component that has access to the method/function that you use in order to decrypt your JSON, then simply call that method/function, passing your JWT as a parameter and from there on you have a JSON as a result from which you can read any field at your discretion.

Maybe you are using jwt-decode, but whatever you use, make sure that it's accessing the correct public key you can decode your JWT with.

Culler answered 6/6 at 17:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.