node.js - 需要 JWT expiresIn 字段以在控制台上显示

标签 node.js mongodb express jwt express-jwt

如何获取 JWT 的到期时间? 我想注意到每个用户的登录 token 的过期时间,现在我可以显示他们的用户 ID、电子邮件 ID,但无法显示过期时间。请指出我应该在哪里编辑代码以显示 expiresIn 字段。

 router.post("/login", (req, res, next) => {
  User.find({ username: req.body.username })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token = jwt.sign(
            {
              username: user[0].username,
              email: user[0].email,
              userId: user[0]._id,
            },
            process.env.JWT_KEY,
            {
              expiresIn: "10h"
            }
          );
          return res.status(200).json({
            message: "Auth successful",
            token: token,
            userId: user[0]._id,
            expiresIn: user[0].exp,
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

这是我现在得到的输出。

{ "message": "Auth successful", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRhcnNoYW4iLCJlbWFpbCI6ImRhcnNoYW5hbi4yNEBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU3MTcxNmRjODlhYzZiNGUyY2E0MTciLCJpYXQiOjE1Mzg5ODEyOTYsImV4cCI6MTUzONn0.k0PVole653f_pB3CrQLtdUmv7-c00x1irbQph2i2XaE", "userId": "5b571716dc89ac6b4e2ca417" , "email": "[email protected]"}

最佳答案

看起来您尚未发送正确的过期响应。

 let expiration = '10h'
 const token = jwt.sign(
            {
              username: user[0].username,
              email: user[0].email,
              userId: user[0]._id,
            },
            process.env.JWT_KEY,
            {
              expiresIn: expiration
            }
          );
          return res.status(200).json({
            message: "Auth successful",
            token: token,
            userId: user[0]._id,
            expiresIn: expiration, //set expiration time
          });

对您有帮助的引用链接:here

关于node.js - 需要 JWT expiresIn 字段以在控制台上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52697010/

相关文章:

javascript - 在 mongodb 中使用 $gt

node.js - 编辑使用 node-cron 创建的任务

javascript - 无法读取未定义 Express API 的属性 'count'

node.js - Passport.js 无法序列化用户

node.js - 如何在node js中将gson转换为json?

node.js - 更改文件时重新启动 Node

javascript - 操作 module.exports 和 require

javascript - 当到达存储在数据库中的 future 日期、时间时,如何在 Node JS 中触发事件?

C# Mongodb 查找集合中最接近的时间

express - Mocha + super 测试 + 断言 : print response body on test failure