【发布时间】:2021-11-27 10:52:22
【问题描述】:
正如您在 NodeJS 代码中看到的那样,我正在从 URL 中提供的 Postman 令牌中获取用户,但我正在努力从给定的令牌号中取回 _id 属性。我想要的是解码后的 id._id 以便我可以在进一步的操作中使用该 id
const jwt = require('jsonwebtoken')
const User = require('../model/users')
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer', '')
const decoded = jwt.verify(token, 'thisisfromabhishek')
`the property _id does not exist on decoded`
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
if (!user) {
throw new Error()
}
req.token = token
req.user = user
next()
} catch (e) {
res.status(401).send({ error: 'Please authenticate.' })
}
}
module.exports = auth
【问题讨论】:
-
你能记录解码变量吗?
-
它没有在控制台中显示任何错误,只是没有从编辑器中获取一些自动完成的 _id 属性,但因此我无法获取 _id
-
你能出示你的令牌吗?
-
“标记”:[{ “标记”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTVlZWY1MmM4NTZlYmFkMTM3NTIzNjIiLCJpYXQiOjE2MzM2MTE2MDJ9.13oo0gCXb_fGyElG4g3Uakf2g7LGdih6fV5pHOK6vkI”, “_id”:的ObjectId( “615eef52c856ebad13752364”)}] 跨度>
-
因此您的令牌存储在 JSON 中。您传递给
jwt.verify(token...的token的确切值是多少?它应该只是令牌本身,eyJhb.....
标签: javascript node.js mongodb jwt