node.js - 具有 jwt 授权的 get 方法返回空对象,我们是否需要解码 jwt token ?

标签 node.js express jwt token decode

路由器和 Controller 代码如下: 尝试使用 jwt 解码器,它提供对象:{_id,iat,exp} 但在 postman 中它返回空对象

===router===
 router.get("/secret", requireSignin, (req, res) => {

   res.json({
     user: req.user,
    });
  });
 
 
 ===controller===
 exports.requireSignin = expressJwt({
   secret: process.env.JWT_SECRET,
   algorithms: ["HS256"],
   userProperty: "auth",
 });```

最佳答案

对我来说,这发生在我没有异步等待一个函数时,该函数将返回我针对 MongoDB 模式编写的签名 token ,就像这样

const sendCustomerToken = (customer, statusCode, res) => { const token = customer.getSignedToken(); res.status(statusCode).json({ success: true, token }); };

基本上,它返回一个 promise ,如果你不等待它,它会返回一个 null 或空对象,因为它是过程性的 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/Empty

但是如果你等待它,它会等待字符串可用的时间然后像这样返回它

const sendCustomerToken = async (customer, statusCode, res) => { const token = await customer.getSignedToken(); res.status(statusCode).json({ success: true, token }); };

https://jwt.io/introduction .

模式方法

customerAuthSchema.methods.getSignedToken = async function() { return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, }); };

您可能希望在查询数据库的代码中检查 promise 。

另外,如果解码不起作用,请尝试使用 jwt sign method 接收有效载荷、 secret 和选项 - 有效载荷是 protected 数据你想返回,secret 是你可以使用 crypto 生成的普通字符串,option 只是你的 token 的生命周期。像这样

function() {
 return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, });};`

像这样的环境变量

PORT=5000 JWT_SECRET=4de5b205fa171927adb1444c06bd990fadd45ffe7a1309def8b5a JWT_EXPIRE=10min

关于node.js - 具有 jwt 授权的 get 方法返回空对象,我们是否需要解码 jwt token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66929705/

相关文章:

node.js - 使用 mongoose 在 mongodb 中存储文件

node.js - 如何使用 mongoose 连接到 mongoDB Atlas

javascript - 为什么不会用node.js设置req.session

json - 使用 jsonwebtoken 登录安全

laravel 5.5 不支持 jwt 授权库

php - 如何在纯 PHP 中创建刷新 token ?

javascript - 早午餐设置 LOGGY_STACKS=true

node.js - 使用 Mongoose 填充其他集合中的记录数

node.js - 通过 npm 导入 Sass

node.js - express-session 中 "saveUninitialized","resave"和 "rolling"属性的确切含义是什么?