Base64url in JSON Web Tokens
How JWTs use Base64url encoding for the header and payload. Learn to decode JWT segments, understand the padding rules, and avoid common JWT mistakes.
Detailed Explanation
JSON Web Tokens (JWTs) use Base64url encoding (not standard Base64) for their header and payload segments. Understanding this encoding is essential for debugging, inspecting, and implementing JWT-based authentication.
JWT structure: A JWT consists of three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- Header (first segment): Base64url-encoded JSON specifying the algorithm and token type.
- Payload (second segment): Base64url-encoded JSON containing the claims (user data, expiration, etc.).
- Signature (third segment): cryptographic signature over the header and payload.
Why Base64url and not standard Base64? JWTs frequently appear in URLs (query parameters, redirect URIs) and HTTP headers. Standard Base64's +, /, and = characters would cause parsing issues in these contexts. Base64url replaces them with URL-safe alternatives.
Decoding a JWT in JavaScript:
function decodeJwtPayload(token) {
const payload = token.split(".")[1];
// Convert Base64url to Base64
const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
// Add padding
const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
// Decode
return JSON.parse(atob(padded));
}
Important nuances:
- JWT Base64url segments never include padding (
=). The RFC 7515 specification explicitly states that padding must be omitted. - The signature segment is also Base64url-encoded, but decoding it gives you raw bytes (not JSON). You only decode the header and payload segments for inspection.
- JWTs are signed, not encrypted (by default). Base64url encoding is not encryption. Anyone can decode and read a JWT's payload. Use JWE (JSON Web Encryption) if the payload contains sensitive data that must be hidden.
Common mistakes:
- Using
atob()directly on JWT segments without converting from Base64url to standard Base64. This produces garbled output or errors. - Assuming the decoded payload is always valid JSON. A malformed or tampered token may produce invalid JSON.
- Decoding a JWT and trusting its contents without verifying the signature. Decoding is trivial; verification is the security step.
Use Case
Building a JWT inspector tool that decodes and displays the header and payload claims of authentication tokens for debugging OAuth 2.0 and OpenID Connect flows.