我使用 Node,我有一个 base64 编码的字符串。 该字符串是一个编码的 JSON 对象,我如何对其进行解码并将其正确解析为 JSON?
我尝试了以下方法,但 bufferedString
中的值不是 JSON 对象字符串。
let splittedString = authenticationToken.split(".");
let bufferedString = Buffer.from(splittedString[2], 'base64').toString('ascii');
let decodedJson = JSON.parse(bufferedString);
谢谢。
最佳答案
JWT 结构:
[signature_or_encryption_algorithm].[payload_as_base64].[verify_signature]
.
有效负载通常是第二个元素,因此使用 splittedString[1]
而不是 2。
但是有更好的方法来处理 jwt token ,您可以使用 jsonwebtoken
模块获取 jwt 的有效负载。
const jwt = require('jsonwebtoken');
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload);
关于javascript - 将jsonwebtoken解码成json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954488/