我是使用JWT和令牌的全新人物;我只是试着这样做:
console.log("logged " + data);
//prints { _id: 5a82ee98e918b22e83d6c3e0,
//username: 'test2',
//name: 'test',
//surname: '2',
//password: '...'
//[etc]
//}
console.log("logged _id " + data._id);
//prints 5a82ee98e918b22e83d6c3e0
var token = jwt.sign(data._id, secret, {
expiresIn: "24h" // expires in 24 hours
});
console.log("saved token " + token);
//prints the token in style eyJhbGciOi[...].eyJfYnNvbn[...].usoLRz-[...]
console.log("decoded: " + JSON.stringify( jwt.decode(token) ) )
//prints the token in this way:
//{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[90,130,238,152,233,24,178,46,131,214,195,224]},"iat":1519502719,"exp":1519589119}
更新: 我在登录功能; data是登录后的答案,它包含登录的用户;我有
var login = function(req, res) {
passport.authenticate('local', function(err, data, info) {
if (err) { console.log(err);
}
console.log("data in auth " + data);
if (!data) {
return res.status(404);
}
req.logIn(data, function(err) {
if (err) {
console.log("err " + err);
}
console.log("logged " + data);
console.log("logged _id " + data._id);
var token = jwt.sign[continues on top]
[...]
}
答案 0 :(得分:1)
您没有正确解码您的令牌
let decodedData = JWT.decode(token,secret);
console.log(decodedData._id);
无需对数据进行字符串化。它会工作正常。如果您收到任何错误,请随时与我联系。
答案 1 :(得分:1)
解决。 问题是我将令牌data._id直接作为字符串输入;正如link所述,必须以这种方式构建令牌有效负载:
{
"_id" : data._id
}
所以我不必这样做:
console.log("logged _id " + data._id);
//WRONG
var token = jwt.sign( data._id, secret, {
expiresIn: "24h"
});
但我必须这样做:
console.log("logged _id " + data._id);
var myId = {
"_id" : data._id
}
var token = jwt.sign( myId, secret, {
expiresIn: "24h"
});
所以现在如果我使用
let decodeddata = jwt.decode(token,secret);
console.log("decoded: " + JSON.stringify(decodeddata,null,4) )
然后这个工作。 感谢所有人帮助我找到问题!