Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API Security APIs APIs From Zero to Real-World API Testing & Automation Authentication JWT Module 5 — API Authentication

JWT (JSON Web Tokens) Explained — Structure, Use, and Pitfalls

Reviewed & accurate
AI Summary

What You'll Learn

  • What a JWT is and why it's so popular
  • The three parts: header, payload, signature
  • How to decode and inspect a JWT
  • Common security pitfalls and best practices

Why This Matters

JWT is the most widely-used token format for APIs. If you work with modern authentication, you will meet JWTs daily. Knowing how to read one, what's inside, and what it can and cannot do is essential for debugging auth issues and for building secure APIs.

Simple Explanation

A JWT (JSON Web Token) is a compact, URL-safe string that carries information between two parties. It has three parts separated by dots:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiQW5pdGEiLCJleHAiOjE3MjQ1NTcyMDB9.abc123signature

Format: header.payload.signature

The Three Parts

1. Header

Base64-encoded JSON describing the token type and signing algorithm:

{
  "alg": "HS256",
  "typ": "JWT"
}

alg tells the server which algorithm was used to sign the token. typ is always "JWT".

2. Payload

Base64-encoded JSON with claims — statements about the user and the token:

{
  "sub": "123",
  "name": "Anita",
  "role": "admin",
  "iat": 1724553600,
  "exp": 1724557200
}

Common claims:

  • sub — subject (usually the user ID)
  • iat — issued at (Unix timestamp)
  • exp — expiration time (Unix timestamp)
  • iss — issuer (who created the token)
  • aud — audience (who the token is for)
  • name, email, role — custom claims

3. Signature

The signature proves the token has not been tampered with. The server computes:

HMACSHA256(
  base64(header) + "." + base64(payload),
  SECRET_KEY
)

Only the server knows SECRET_KEY. If anyone changes the payload, the signature no longer matches, and the server rejects the token.

How JWT Authentication Works

  1. User logs in with username/password.
  2. Server verifies credentials and creates a JWT with the user's ID and role.
  3. Server signs the JWT with its secret key and returns it to the client.
  4. Client stores the JWT (localStorage, cookie, etc.) and sends it as Authorization: Bearer <jwt> on every subsequent request.
  5. Server verifies the signature — if it matches, the server trusts the payload. No database lookup needed.
  6. Server checks expiration (exp) and other claims.

Why JWTs Are Popular

  • Stateless. The server does not need to store sessions. The token contains everything.
  • Self-contained. User ID, role, and expiration are all in the token.
  • Portable. Works across multiple services and domains.
  • Compact. Small enough to fit in a URL, header, or cookie.

Decoding a JWT

You can decode the first two parts (header and payload) yourself — they're just Base64-encoded JSON. Try this in your browser console:

const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiQW5pdGEiLCJleHAiOjE3MjQ1NTcyMDB9.abc123";

const parts = token.split(".");
const header  = JSON.parse(atob(parts[0]));
const payload = JSON.parse(atob(parts[1]));

console.log("Header:", header);
console.log("Payload:", payload);

Or use the debugger at jwt.io — paste any JWT and see its decoded contents.

Important: Anyone can decode a JWT. The payload is Base64, not encrypted. Never put secrets (passwords, API keys) in a JWT payload. The signature only prevents tampering, not reading.

Common Security Pitfalls

1. Storing sensitive data in the payload

The payload is readable by anyone. Do not put passwords, secrets, or PII in a JWT. Use only the user ID and minimal context.

2. Using "alg": "none"

JWT supports an algorithm called "none" that produces no signature. Some vulnerable libraries accept tokens with "alg": "none" — meaning anyone can forge a token. Always reject tokens with alg: none in your library.

3. Long-lived tokens

A JWT cannot be revoked before its exp — it's valid until expiration. If a token is stolen, the thief has access until it expires. Keep expirations short (15 minutes to 1 hour) and use refresh tokens for long sessions.

4. Weak signing keys

If the signing key is weak or guessable, attackers can forge tokens. Use a strong, random secret of at least 256 bits.

5. Storing JWTs in localStorage

localStorage is vulnerable to XSS attacks. Malicious JavaScript can read it. For high-security apps, store JWTs in HttpOnly cookies that JavaScript cannot access.

6. Trusting client-side role claims

Just because a JWT says "role": "admin" does not mean the user is an admin — the server must verify the signature and trust only the claims it issued.

JWT vs Opaque Tokens

AspectJWTOpaque token (random string)
Self-contained?Yes — contains user dataNo — server must look up in DB
VerificationVerify signature, no DB lookupLook up in DB or cache
RevocationHard — valid until expEasy — delete from DB
SizeLarge (1–2 KB)Small (32–64 bytes)
Use caseDistributed systems, microservicesSingle server, easy revocation needed

Common Mistakes

  1. Treating JWTs as encrypted. They are signed, not encrypted. Anyone can read the payload.
  2. Putting PII in the payload. Email, phone, address — all readable by anyone with the token.
  3. Long expirations. A 30-day JWT is a 30-day security risk if stolen. Use 1-hour tokens + refresh tokens.
  4. Not validating the signature. Some beginners decode the payload and trust it. Always verify the signature server-side.
  5. Allowing alg: none. Reject any token with this algorithm.
  6. Sharing the secret key across services. Use asymmetric keys (RS256) for multi-service setups.

Practical Exercise (10 minutes)

  1. Get a sample JWT (you can generate one at jwt.io).
  2. Decode the header and payload using the JavaScript snippet above or jwt.io.
  3. Identify the sub, iat, and exp claims.
  4. Convert the exp Unix timestamp to a human-readable date. (Hint: new Date(1724557200 * 1000) in JS.)
  5. Modify the payload (e.g., change role to "admin") and observe that the signature no longer matches.

Mini Challenge

Build a simple login flow in any language: (1) an endpoint that takes username/password and returns a JWT signed with a secret, (2) a protected endpoint that verifies the JWT and returns user info from the payload. Test with cURL. Use a library — never implement JWT signing yourself.

Key Takeaways

  • JWT = header.payload.signature, separated by dots.
  • Header and payload are Base64-encoded JSON — anyone can read them.
  • Signature is computed with a secret key — prevents tampering, not reading.
  • Keep tokens short-lived (1 hour). Use refresh tokens for longer sessions.
  • Never put secrets or PII in the payload. Never allow alg: none. Always verify the signature server-side.
Course continuity
Previously: Lesson 28 covered Basic Auth and Bearer tokens.
Today: You learned JWT — the most common Bearer token format.
Next: Lesson 30 covers OAuth 2.0 — the protocol that issues JWTs in real-world apps.

FAQ

Should I use HS256 or RS256?

HS256 uses a shared secret — both signing and verification use the same key. RS256 uses asymmetric keys — sign with a private key, verify with a public key. Use RS256 when multiple services need to verify tokens without sharing the signing key.

How do I revoke a JWT before it expires?

You can't — JWTs are stateless. Workarounds: (1) keep a blacklist of revoked tokens (defeats statelessness), (2) use very short expirations, (3) use refresh tokens that can be revoked, with short-lived access tokens.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments