节点无法生成JWT

时间:2020-07-17 20:09:47

标签: node.js mongoose jwt

我正在使用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
});

2 个答案:

答案 0 :(得分:0)

使用功能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变量被设置为非常接近零的值。因此,它的生成在生成和验证之间经过的时间内都是无效的。

答案 1 :(得分:0)

不要使用arrow函数,将normal函数用于模式方法

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

根据文档

请勿使用ES6箭头函数(=>)声明方法。箭头功能 明确禁止绑定此内容,因此您的方法将无权访问 文档,上面的示例将不起作用。

链接here

由于上述this._id的原因未被设置,因此当您尝试对其进行验证时,总是undefined