简体   繁体   English

如何从 Node.js 中的 jwt 令牌获取 user.id?

[英]How to get user.id from jwt token in Node.js?

In my User controller, I create a token in which I save this user's id when he login to my application.在我的用户控制器中,我创建了一个令牌,当他登录到我的应用程序时,我将在其中保存该用户的 ID。

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.现在在另一个控制器中,我想读取此 ID 并将其用于我的目的。 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`);
            });

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). 该中间件应负责验证登录后从客户端代码传递的传入令牌(通常将令牌存储在cookie中)。

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: 然后,最后在即将到来的控制器中,您可以从请求对象访问ID:

   const loginId = req.userId;

    Bill.update(
      {
        available_funds: available_funds - amountMoney,
      },
      { where: { id_owner: loginId } },
    ).then(() => {
      res.status(200).send(`ok`);
    });

You don't need to add extra codes.您不需要添加额外的代码。 To access the userId use this:要访问 userId 使用这个:

req.payload.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM