JSON Web Tokens—defined in RFC 7519—power authentication and authorization across modern REST APIs, single-page applications, mobile backends, and OpenID Connect identity providers. Unlike opaque session IDs that force every microservice to query a central Redis or SQL session table on every API call, a signed JWT carries verifiable user claims directly inside the token itself.
That stateless convenience comes with sharp edges. Misconfigured signature checks, oversized payloads, or storing tokens in unsafe browser locations can expose an entire API. In this guide, we examine JWT anatomy down to the byte level, compare symmetric and asymmetric signing algorithms, and walk through battle-tested security patterns. If you want to inspect a token offline right now, open our Browser-Only JWT Decoder.
- 1. Anatomy of a Compact JWT (Header, Payload, Signature)
- 2. Signed (JWS) vs. Encrypted (JWE) Tokens
- 3. Registered, Public, and Private Claims
- 4. Signing Algorithms: HS256 vs. RS256 vs. ES256 / EdDSA
- 5. How Verification Works Under the Hood
- 6. Classic JWT Security Pitfalls & How to Prevent Them
- 7. Browser Storage, Short Lifetimes & Refresh Rotation
- 8. When Should You Use Server Sessions Instead?
1. Anatomy of a Compact JWT (Header, Payload, Signature)
A standard signed JWT (technically a JWS, or JSON Web Signature) is an ASCII string made of three Base64URL-encoded parts joined by two periods (.):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfNDg5MjEiLCJyb2xlIjoiZGV2ZWxvcGVyIiwiaWF0IjoxNzM1Njg5NjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- Header (Part 1): A small JSON object declaring the signing algorithm (
alg), token type (typ), and optionally a key ID (kid) for key rotation:{ "alg": "RS256", "typ": "JWT", "kid": "auth-2026-11" } - Payload (Part 2): A JSON object holding claims—statements about the authenticated subject, permissions, and token validity window.
- Signature (Part 3): A cryptographic tag computed over the ASCII string
base64url(header) + "." + base64url(payload). If an attacker changes even one character in the payload (for example, changing"role":"user"to"role":"admin"), the signature no longer matches and the server rejects the token.
Notice that Base64URL encoding simply converts + to -, / to _, and strips trailing = padding so tokens travel cleanly inside HTTP Authorization: Bearer <token> headers and URLs. You can explore this encoding mechanism in our Base64 Encoding Guide.
2. Crucial Distinction: Signed (JWS) vs. Encrypted (JWE)
The number-one misconception among beginners is thinking a JWT hides its contents. In a standard 3-part JWS, the header and payload are signed (tamper-proof), not encrypted. Anyone who intercepts the token—or even the logged-in user inspecting browser DevTools—can Base64URL-decode the payload in one millisecond.
Therefore, never place passwords, API secrets, database connection strings, or sensitive personal data (like Aadhaar/SSN numbers) inside a standard JWT payload. If a token truly must carry confidential claims unreadable by the client, you need a 5-part JWE (JSON Web Encryption) token—or better yet, keep sensitive attributes in your backend database and include only an opaque user ID (sub) in the JWT.
3. Registered, Public, and Private Claims
RFC 7519 defines three categories of payload keys ("claims"). Keeping your claims concise matters because every HTTP request carries the full JWT in its header:
| Claim | Type | Description & Validation Rule |
|---|---|---|
iss | Registered | Issuer: Auth service URL (e.g. https://auth.example.com). Must match expected issuer. |
sub | Registered | Subject: Unique immutable user ID (prefer UUIDs over mutable emails). |
aud | Registered | Audience: Target API identifier so a token minted for App A cannot be replayed against App B. |
exp | Registered | Expiration Time: Unix epoch seconds after which the token must be rejected. |
nbf | Registered | Not Before: Optional Unix timestamp before which the token is not yet valid. |
iat | Registered | Issued At: Unix timestamp when the token was minted. |
jti | Registered | JWT ID: Unique token identifier useful for one-time-use tokens or revocation lists. |
4. Signing Algorithms: HS256 vs. RS256 vs. ES256 / EdDSA
Picking the right cryptographic algorithm depends on whether the same server mints and verifies tokens, or whether multiple independent services need to verify tokens issued by a central identity provider:
| Algorithm | Key Type | How Verification Works | Best Use Case |
|---|---|---|---|
| HS256 (HMAC-SHA256) | Symmetric (1 shared secret) | Issuer and verifier share the exact same 256-bit+ secret string. | Single monolith backend where one service issues and verifies tokens. |
| RS256 (RSA-SHA256) | Asymmetric (Private + Public key) | Auth server signs with Private Key; any service verifies via Public Key (JWKS). | Microservices, OAuth 2.0 / OIDC, third-party API gateways. |
| ES256 / EdDSA | Asymmetric (Elliptic Curve) | Same public-key model as RS256, with much smaller signatures and faster signing. | Modern high-throughput APIs and mobile/edge services. |
If you use symmetric HS256, never use a short human password like "mysecret123"—offline brute-force tools like Hashcat can crack weak HMAC secrets rapidly. Generate at least 32 cryptographically random bytes (openssl rand -base64 32).
5. How Verification Works Safely in Code
Always rely on a well-maintained JWT library (such as jose in Node.js or PyJWT in Python) rather than writing manual crypto checks. Crucially, notice how a safe verifier explicitly pins algorithms, issuer, and audience:
// Example using the modern "jose" library in Node.js
import { jwtVerify, createRemoteJWKSet } from "jose";
const JWKS = createRemoteJWKSet(
new URL("https://auth.example.com/.well-known/jwks.json")
);
export async function verifyAccessToken(token) {
const { payload } = await jwtVerify(token, JWKS, {
issuer: "https://auth.example.com",
audience: "https://api.example.com",
algorithms: ["RS256", "ES256"], // Never trust the header's "alg" blindly!
clockTolerance: 5 // Allow 5 seconds of clock skew
});
return payload;
}
6. Classic JWT Security Pitfalls & How to Prevent Them
The "alg": "none" Attack
The JWT specification allows an unsecured "alg": "none" header for environments where integrity is already guaranteed externally. Historically, vulnerable libraries read header.alg from the incoming untrusted token, saw "none", skipped signature verification entirely, and accepted forged admin payloads. Fix: Explicitly pass an allowlist like algorithms: ["RS256"] to your verification function and reject none.
Algorithm Confusion (RS256 Downgraded to HS256)
If a server supports both RSA and HMAC and naively passes the RSA public key as the verification key based on whatever alg the client puts in the header, an attacker can download the publicly visible RSA public key, sign a forged payload with HS256 using that public key bytes as the HMAC secret, and fool the server! Pinning expected algorithms completely eliminates this attack.
Missing kid Validation (Path Traversal / SQLi)
Some custom servers read the kid (Key ID) header field and immediately load a file from disk (fs.readFile(`/keys/${header.kid}`)) or run a SQL query without sanitizing it. Always treat kid as untrusted user input and map it against an explicit in-memory allowlist or JWKS dictionary.
7. Browser Storage, Short Lifetimes & Refresh Token Rotation
Because stateless JWTs cannot be deleted on the server prior to exp unless you introduce a revocation database check, **short access-token lifetimes (5 to 15 minutes)** are your primary defense against stolen tokens.
For browser web apps, avoid storing long-lived tokens in localStorage or sessionStorage, because any Cross-Site Scripting (XSS) bug—even in a third-party analytics script—can read localStorage and exfiltrate the token. Instead:
- Store refresh tokens inside
HttpOnly; Secure; SameSite=Lax(orStrict) cookies so client-side JavaScript cannot read them. - Implement Refresh Token Rotation: each time a refresh token exchanges for a new access token, invalidate the old refresh token and issue a fresh one. If a stolen refresh token is replayed twice, the auth server detects reuse and immediately revokes the entire token family.
- Keep access tokens in JavaScript memory (React state / closure) or inside an
HttpOnlycookie paired with CSRF protection.
8. When Should You Use Traditional Sessions Instead?
Despite JWT's popularity, traditional opaque session cookies backed by Redis are often simpler and safer for standard monolithic web applications:
- Instant Revocation: Need a "Log out of all devices" button or instant account suspension when an admin bans a user? With Redis sessions, deleting one key takes effect immediately across every endpoint.
- Zero Bloat on Cookies: An opaque session ID is ~32 bytes, whereas a JWT loaded with roles and permissions can easily grow to 1–2 KB on every image or API request.
- Use JWTs where they shine: Cross-domain SSO (OpenID Connect), federated microservices where downstream APIs should not hit the auth database on every call, and short-lived mobile/CLI bearer authorization.
9. Production JWT Rollout & Debugging Checklist
Before deploying JWT authentication to production or debugging a mysterious 401 Unauthorized error between microservices, run through this checklist:
- Check Server Clock Synchronization (NTP): Even a 60-second clock drift between your auth server and API gateway causes
iat/nbf/expvalidation failures. Configure NTP across all containers and allow a smallclockTolerance(5–15 seconds). - Inspect Token Claims Locally First: Paste failing tokens into our Browser-Only JWT Decoder to verify that
exphasn't elapsed andaudmatches your exact API identifier. - Rotate Signing Keys with
kid: Always include a key ID (kid) in your JWT header and publish multiple active public keys on your JWKS endpoint so you can rotate keys gracefully without logging everyone out at once. - Keep Payloads Lean: Avoid stuffing long permission matrices or user avatars into claims. An HTTP header exceeding 8 KB triggers
431 Request Header Fields Too Largeerrors on Nginx, Cloudflare, and corporate proxies. - Use HTTPS Everywhere: Never transmit Bearer JWTs over unencrypted
http://links, and never pass JWTs inside URL query strings (?token=eyJ...), where they leak into browser history, server access logs, and HTTPRefererheaders.
10. Verifying JWTs in Python & Node.js Middleware
Whether your API runs on Express/Fastify in Node.js or FastAPI/Django in Python, your authentication middleware should follow the same defensive pattern: extract the Bearer token strictly from the Authorization header, verify the cryptographic signature against an explicit algorithm allowlist, and map missing or expired tokens to clean 401 Unauthorized responses.
# Python (PyJWT): Safe JWT Verification Example
import jwt
from jwt import InvalidTokenError
PUBLIC_KEY = open("public_rsa.pem").read()
def verify_bearer_token(auth_header: str) -> dict:
if not auth_header or not auth_header.startswith("Bearer "):
raise ValueError("Missing Bearer token")
token = auth_header.split(" ", 1)[1].strip()
try:
payload = jwt.decode(
token,
PUBLIC_KEY,
algorithms=["RS256"], # Explicit allowlist prevents alg=none/HS256 confusion
audience="https://api.techcar.online",
issuer="https://auth.techcar.online",
leeway=10
)
return payload
except InvalidTokenError as exc:
raise ValueError(f"Invalid or expired JWT: {exc}")
Notice the explicit audience, issuer, and algorithms=["RS256"] arguments. Skipping audience validation is a subtle vulnerability in multi-tenant platforms: a valid token issued by your identity server for a low-privilege service could otherwise be replayed against your billing or admin microservice.
11. Handling Instant Logout & Token Revocation
The biggest operational challenge with stateless JWTs is immediate revocation when a user resets their password, reports a stolen laptop, or clicks "Log out of all devices." Three practical hybrid patterns solve this without abandoning JWT benefits:
- Short Access TTL + Revocable Refresh Token: Keep access JWTs at 5 minutes and store refresh tokens in Redis/PostgreSQL. Logging out deletes the refresh token immediately, limiting any stolen access token to at most 5 minutes.
jtiDeny-List in Redis: Store revoked token IDs (jti) in Redis with a TTL matching the token's remaining lifetime untilexp. Since only revoked tokens enter Redis, the lookup table stays tiny and fast.- Per-User
tokenVersionCounter: Store an integertokenVersionin your user record and include it inside the JWT claims. Incrementing the user'stokenVersionon password change invalidates every previously minted token for that user in one database write.
Frequently Asked Questions
Why is it unsafe to paste real JWTs into random online decoders?
Any active token gives whoever holds it access until exp expires. If a server-backed decoder logs HTTP parameters or request bodies, an operator could replay your token. Our TechCar DevTools JWT Decoder runs 100% locally in browser memory with zero network uploads.
What happens if a JWT is missing the third signature segment?
Standard signed JWS tokens require 3 dot-separated parts (header.payload.signature). Tokens missing a signature are either unsecured alg: none tokens (which APIs must reject) or malformed strings.
How are iat and exp numbers calculated?
Both claims store NumericDate values: the integer count of seconds since January 1, 1970 UTC (Unix epoch). Note that JavaScript's Date.now() returns milliseconds, so divide by 1000 when checking JWT timestamps manually.
Should I store user permissions inside the JWT?
Coarse-grained roles (like "plan": "pro") work well, but fine-grained permissions that change frequently (or hundreds of resource IDs) bloat headers and stay stale until token expiration. Check granular ACLs on the server when immediate enforcement matters.