decrypt jwt in javascript

To decrypt a JWT (JSON Web Token) in JavaScript, you first need to split the token into its three parts: the header, the payload, and the signature.

index.tsx
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const [header, payload, signature] = token.split('.');
228 chars
3 lines

Next, you need to decode the base64-encoded header and payload:

index.tsx
const decodedHeader = atob(header);
const decodedPayload = atob(payload);
74 chars
3 lines

Then, you can parse the JSON data from the decoded header and payload:

index.tsx
const parsedHeader = JSON.parse(decodedHeader);
const parsedPayload = JSON.parse(decodedPayload);
98 chars
3 lines

Finally, you need to verify the signature using a cryptographic algorithm that matches the one used to sign the token, and the secret or public key that was used to create the signature. Here is an example using the jsonwebtoken library:

index.tsx
const jwt = require('jsonwebtoken');

const secret = 'mysecret';

jwt.verify(token, secret, (err, decoded) => {
  if (err) {
    console.error(err);
  } else {
    console.log(decoded);
  }
});
194 chars
12 lines

This will log the decoded payload object if the signature is valid and the secret matches. Note that if the token has expired or was revoked, you may need to check the exp and iat claims in the payload to ensure that it is still valid.

gistlibby LogSnag