【问题标题】:Node cannot generate JWT节点无法生成 JWT
【发布时间】:2020-11-07 16:22:46
【问题描述】:

我正在使用jsonwebtoken 包来生成 jwt 令牌。

这是我的用户模型

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  }
})

这是为每个用户生成令牌的用户模式方法:

userSchema.methods.generateAuthToken = () => { 
  var token = jwt.sign({ _id: this._id}, 'shhhhh');
  return token
}

但是,在运行这段代码来验证令牌时,在记录有效负载时,我会记录 undefined 而不是有效负载。有人知道为什么吗?

jwt.verify(token, 'shhhhh', function(err, decoded) {
    if (err) console.log(err)
    console.log(decoded._id) // bar
});

【问题讨论】:

    标签: node.js mongoose jwt


    【解决方案1】:

    当您使用函数 jwt.sign 时,您必须设置到期时间。

    这是一个例子:

    exports.logEmployee = (req, res) => {
        res.status(200).json({ token: 'Bearer ' + jwt.sign(req.employee, process.env.SECRET, { expiresIn: 1800 }) });//expires in 1800 seconds
        res.end();
    };
    

    我相信在您的情况下,expiresIn 变量被设置为非常接近零的值。所以它生成了,同时在生成和验证之间经过的时间是无效的。

    【讨论】:

      【解决方案2】:

      不要使用arrow 函数,将normal 函数用于您的架构方法

      userSchema.methods.generateAuthToken = function() { 
        var token = jwt.sign({ _id: this._id}, 'shhhhh');
        return token
      }
      

      根据文档

      不要使用 ES6 箭头函数 (=>) 声明方法。箭头函数 明确阻止绑定 this,因此您的方法将无权访问 到文档中,上面的例子将不起作用。

      链接here

      由于上述原因,您的this._id 未设置,因此当您尝试验证时,它始终为undefined

      【讨论】:

        猜你喜欢
        • 2018-11-02
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        • 2022-01-14
        • 2017-10-03
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        相关资源
        最近更新 更多