How can I decode the payload of JWT using JavaScript? Without a library. So the token just returns a payload object that can consumed by my front-end app.
Example token: xxxxxxxxx.XXXXXXXX.xxxxxxxx
And the result is the payload:
{exp: 10012016 name: john doe, scope:['admin']}
Note: this does not validate the signature, it just extracts the JSON payload from the token, which could have been tampered with.
Working unicode text JWT parser function:
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
JWT uses base64url
(RFC 4648 §5), so using only atob
(which uses base64
) isn't enough.
function parseJwt (token) {
return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
}