Wednesday, 19 June 2019

Decoding JWTs

Ever wonder how to decode a JWT token to get at the email address and user name?  Given that you have the openid, email, and profile scopes granted.


Visit JWT.io for decoder and doc.

Of if you love (trust?) Microsoft, ADFS JWT Decoder.

And the full blown specifation on RFC7519...

And then the openid documentation on how to get name and email.


     // header, payload, signature
     function parseJwt (token) {
            let ary = token.split('.');
            if( ary.len != 3)
                {
                console.log( "not a JWT: " + token );
                return undefined;
                }
            // assume it IS urlEncoded
            let base64Url = ary[1];
            let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            let txt = Buffer.from(base64, 'base64').toString();
            return JSON.parse( txt ); 
        };

And then

let jwt = parseJwt(tokenStr);
let email = jwt.email || jwt.upn || 'unknown';
let name = jwt.name;
console.log( `You are ${name} at ${email}` );