Wednesday 19 June 2019

Decoding JWTs and Bot Service Auth tokens

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


But there is more cool stuff you can do via Bot Framework! For example, want to re-use an Auth Token? Use this class to send off requests piggy-backing (using on-behalf-of) on the Bot's app registration.

Then, you can also use Bot Framework's JWT decoder in C#. Use this class to decode the properties into a hashmap.