David Faizulaev
David Faizulaev

Reputation: 5721

Decode jsonwebtoken into json object

I working with Node and I have a string which is base64 encoded. The string is an encoded JSON object, how can I decode it and parse it to JSON properly?

I've tried the following but the value in bufferedString is not the JSON object string.

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

Thanks.

Upvotes: 1

Views: 2081

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

JWT Structure:

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

The payload usually is the second element so use splittedString[1] instead of 2.

But there are better approaches to work with jwt tokens, you can get the payload of a jwt by using jsonwebtoken module.

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

Upvotes: 2

Related Questions