Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

jwt

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']} 
like image 644
Chrisk8er Avatar asked Jul 24 '16 12:07

Chrisk8er


People also ask

How do I read JWT payload?

Each JWT contains a payload. The payload is a base64 encoded JSON object that sits between the two periods in the token. We can decode this payload by using atob() to decode the payload to a JSON string and use JSON. parse() to parse the string into an object.


2 Answers

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); }; 
like image 143
Peheje Avatar answered Oct 13 '22 15:10

Peheje


Simple function with try - catch

const parseJwt = (token) => {   try {     return JSON.parse(atob(token.split('.')[1]));   } catch (e) {     return null;   } }; 

Thanks!

like image 33
Rajan Maharjan Avatar answered Oct 13 '22 14:10

Rajan Maharjan