首页 > 解决方案 > 将 jsonwebtoken 解码为 json 对象

问题描述

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

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

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

谢谢。

标签: javascriptnode.jsbase64

解决方案


智威汤逊结构:

[signature_or_encryption_algorithm].[payload_as_base64].[verify_signature].

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

但是有更好的方法来处理 jwt 令牌,你可以通过使用jsonwebtokenmodule.

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);

推荐阅读