How to decode jwt token in javascript without using a library?

Chrisk8er picture Chrisk8er · Jul 24, 2016 · Viewed 214.7k times · Source

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']}

Answer

Peheje picture Peheje · Jul 24, 2016

Working unicode text JWT parser function:

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
};