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']}
解决方案
Will this work?
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
};
As mentioned in the comments by Racing Tadpole javascript replace only replaces first occurence, use regular expression instead:
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');