Instantly share code, notes, and snippets.

@benhowes /info.md
Last active Nov 20, 2018

Embed
What would you like to do?
Simple JWT decoder

Gets a JS object which contains the decoded body of the JWT. For now I am pasting this in to postman tests when I need to get JWT decoding

#Important Does not validate the token at all!

function jwt_decode(jwt){
var parts = null;
try{
parts = decode_b64(jwt.split('.')[1]);
} catch (e){
console.log("error parsing JWT");
throw (e)
}
console.log(parts)
if (parts){
return JSON.parse(parts);
}
return {};
}
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error();
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
function atob (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
function b64DecodeUnicode(str) {
return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = '0' + code;
}
return '%' + code;
}));
}
function decode_b64(str) {
var output = str.replace(/-/g, "+").replace(/_/g, "/");
switch (output.length % 4) {
case 0:
break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default:
throw "Illegal base64url string!";
}
try{
return b64DecodeUnicode(output);
} catch (err) {
return atob(output);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment