【问题标题】:How to get user.id from jwt token in Node.js?如何从 Node.js 中的 jwt 令牌获取 user.id?
【发布时间】:2019-05-22 16:14:28
【问题描述】:

在我的用户控制器中,我创建了一个令牌,当他登录到我的应用程序时,我将在其中保存该用户的 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 });
    });
};

现在在另一个控制器中,我想读取这个 id 并将其用于我的目的。我怎样才能得到它?

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

【问题讨论】:

标签: javascript node.js jwt


【解决方案1】:

制作一个中间件,在转发到更新路由之前检查传入的令牌。 该中间件应负责验证您在登录后从客户端代码传递的传入令牌(通常将令牌存储在 cookie 中)。

现在在您的中间件中,您可以执行类似的操作:

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

然后,最后在即将到来的控制器中,您可以从请求对象中访问 id:

   const loginId = req.userId;

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

【讨论】:

    【解决方案2】:

    您无需添加额外的代码。要访问 userId,请使用:

    req.payload.id
    

    【讨论】:

    • Si es necesario, el payload saldria undefined.
    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2018-01-13
    • 2021-07-12
    • 2021-01-19
    • 1970-01-01
    • 2019-10-23
    • 2020-05-05
    • 2021-07-05
    相关资源
    最近更新 更多