最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get user.id from jwt token in Node.js? - Stack Overflow

programmeradmin2浏览0评论

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 (bcryptpareSync(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`);
            });

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.pareSync(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`);
            });
Share Improve this question edited Dec 22, 2018 at 18:28 Nandini Venkateshan 2573 silver badges9 bronze badges asked Dec 22, 2018 at 16:43 user10713925user10713925 1
  • Possible duplicate of NodeJs - Retrieve user infor from JWT token? – sadrzadehsina Commented Dec 22, 2018 at 16:49
Add a ment  | 

2 Answers 2

Reset to default 8

Make a middleware which checks the ining token before forwarding to your update route. This middleware should be responsible for validating the ining token which you pass from the client side code after logging in (storing token in cookies is monly 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 uping 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`);
    });

JWT is an encrypted JSON. So, if you have the JWT and you have another ponent 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.

发布评论

评论列表(0)

  1. 暂无评论