【问题标题】:Javascript Tokens, JWT and numbers when decoded解码时的 Javascript 令牌、JWT 和数字
【发布时间】:2018-08-04 15:36:56
【问题描述】:

我对使用 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}
  1. 为什么不以纯文本形式打印身份证号?
  2. 如何获取我放入令牌的 ID 号?

更新: 我在登录功能; 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]
    [...]
}

【问题讨论】:

  • 在签署之前如何将声明分配给 jwt?这似乎是相关的。
  • 我在登录功能; data 是登录后的答案,它包含登录的用户;我在顶帖上添加了代码

标签: javascript jwt token


【解决方案1】:

你没有正确解码你的令牌

let decodedData = JWT.decode(token,secret);
console.log(decodedData._id);

无需对数据进行字符串化。它会正常工作。如果您遇到任何错误,请随时与我联系。

【讨论】:

  • 感谢您的回答;我完全忘了添加secret ...无论如何它不起作用,它会打印 [Object Object] 并对其进行字符串化得到数字...
  • 没问题,这都是我的荣幸。
  • 不要把它串起来。
【解决方案2】:

解决了。 问题是我将令牌 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) )

然后这工作。 感谢大家帮我找到问题!

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2018-10-05
    • 2019-05-19
    • 2017-01-22
    • 2018-08-14
    • 2020-05-23
    • 2016-11-15
    • 2021-06-30
    相关资源
    最近更新 更多