Explain Codes LogoExplain Codes Logo

Decoding JWT token in JavaScript without using a library

javascript
jwt
base64
url-decoding
Nikita BarsukovbyNikita Barsukov·Dec 24, 2024
TLDR

Parsing a JWT token in JavaScript is a piece of cake using built-in functions. Leverage the atob() function for base64 decoding and JSON.parse() to convert strings to objects. To get both the header and payload parts, use this simple trick:

const tokenParts = token.split('.'); // Expecto Patronum! Let's split our token into pieces const decodedHeader = JSON.parse(atob(tokenParts[0])); // Whoa, a decoded header just appeared! const decodedPayload = JSON.parse(atob(tokenParts[1])); // Voila! The payload is decoded too

Both decodedHeader and decodedPayload will hold the JWT data you are seeking. Be smart about handling errors for effective and robust parsing.

When it comes to JWTs, it's not all unicorns and rainbows. Watch out for these typical challenges while decoding:

  • Token Structure: Make sure your JWT is properly formatted with two dots dividing the three parts. Anything else is not kosher.
  • Padding Characters Issue: Depending on your base64 decoding strategy, beware of base64 padding characters (=) slipping in.
  • Character Encoding: JWTs use base64url encoding, which is slightly different from standard base64. Replace + with - and / with _ before decoding.
  • URL De-coding: If we are dealing with an URL-encoded token, it must be URL-decoded first.

And remember, atob() might not be available in some environments like Node.js, but you still have a friend in Buffer:

const base64 = require('base64url'); const decodedPayload = JSON.parse(base64.decode(tokenParts[1])); // One Node.js equivalent of atob() coming right up!

Dive deeper into JWTs

Understanding JWT structure

A JWT is made of three parts: the header, payload, and signature. Each part is base64url-encoded and separated by dots. While the header has information about the token type and the algorithm used, the payload carries the claims – desirable data like user info, permissions, and more.

Security is no joke

Decoding is cool, but it's only half the battle. This method will not validate the signature. Make sure you take care of this using an appropriate server-side authentication mechanism. Without this step, any changes in the token pass unnoticed. Not on my watch!

Real-world applications

Decoded JWTs are useful for frontend applications. Displaying user details, checking user permissions, or managing states – all these are great use cases. But remember the golden rule – trust but verify. Always validate the JWT server-side before you trust its data.

References