将base64字符串解码为JSON对象

时间:2019-05-02 14:20:42

标签: javascript node.js base64

我正在使用Node,并且我有一个以base64编码的字符串。 该字符串是经过编码的JSON对象,如何解码并将其正确解析为JSON?

我尝试了以下操作,但是bufferedString中的值不是JSON对象字符串。

let splittedString = authenticationToken.split(".");
let bufferedString = Buffer.from(splittedString[2], 'base64').toString('ascii');
let decodedJson = JSON.parse(bufferedString);

谢谢。

1 个答案:

答案 0 :(得分:2)

JWT结构:

[signature_or_encryption_algorithm].[payload_as_base64].[verify_signature]

有效载荷通常是第二个元素,因此请使用splittedString[1]而不是2。

但是有更好的方法来处理jwt令牌,您可以使用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);