Mahesh
Mahesh

Reputation: 221

Decode Jwt Token in Node - without Library

I have a following code to decode the Jwt token in Javascript (ref: How to decode jwt token in javascript)

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

function parseJwt(token) {
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  console.log(JSON.parse((atob(base64))))
};

parseJwt(token);

I am getting the payload which I needed from above code But I am implementing it in node where we dont have "atob" function to decode the base64 encoded string

Seems we need to use Buffer in node. Did my research and came up with below solution which didn't work.

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
function parseJwt(token) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const buff = new Buffer(base64, 'base64');
  const payloadinit = buff.toString('ascii');
  const payload = JSON.parse(payloadinit);
  console.log(payload)
};
parseJwt(token);

Please let me know if there is any better approach - No libraries(Jwt, or decode-Jwt)

Upvotes: 1

Views: 12962

Answers (2)

Kashan Haider
Kashan Haider

Reputation: 1204

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

simple & easy way

Upvotes: 2

Mahesh
Mahesh

Reputation: 221

Actually I have tried it in independent environment and above code works like charm for getting Jwt token pay load

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'

const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const buff = new Buffer(base64, 'base64');
const payloadinit = buff.toString('ascii');
const payload = JSON.parse(payloadinit);
console.log(payload);

https://repl.it/@Punith/RuralSeveralAdaware

Upvotes: 8

Related Questions