How to Decode JWT Tokens: A Comprehensive Step-by-Step Guide
JSON Web Tokens (JWT) are the backbone of modern web authentication. In this guide, we'll break down their anatomy, explain how they're encoded, and show you how to safely decode them manually or with code.
What Exactly is a JWT?
At its core, a JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
JWTs are most commonly used for **Authentication** and **Information Exchange**. Once a user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
The Anatomy of a JWT
A single JWT string is always composed of three distinct parts separated by dots (.):
- Header: Contains the type of the token and the signing algorithm being used (e.g., HS256).
- Payload: Contains the actual "claims" (data) about the user and any additional metadata like expiration time (
exp). - Signature: Used to verify that the sender of the JWT is who it says it is and to ensure that the message was't changed along the way.
header.payload.signature
Step 1: Decoding the Header
The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
To decode it, you simply take the first part of the token (before the first dot) and use a Base64Url decoder. Since it is not encrypted (only encoded), anyone who can see the token can decode it.
Step 2: Inspecting the Payload
The payload is the middle part of the token. It contains the claims, which are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
Crucial Security Tip: Never store sensitive information (like passwords or private keys) in the JWT payload, as it is easily decoded by anyone who has the token string.
Step 3: Verifying the Signature
While decoding is easy, Verifying is critical. The signature is created by taking the encoded header, the encoded payload, a secret, the algorithm specified in the header, and signing that.
If you change even a single character in the header or payload, the signature will no longer match, allowing your backend to reject the tampered token immediately.
Summary
Decoding a JWT is as simple as splitting the string by dots and running the segments through a Base64Url decoder. However, real-world applications must always use a trusted library to verify the digital signature before trusting the data inside the payload.