JWT Introduction — What JSON Web Tokens Are and How They Work
In this tutorial, you will learn about JWT Introduction. We cover key concepts, practical examples, and best practices to help you master this topic.
JWT (JSON Web Token) is a compact, URL-safe token format defined by RFC 7519 for securely transmitting claims between parties as a signed JSON object.
What You'll Learn
What JWT is, its three-part structure, how cryptographic signing ensures integrity, and why JWT became the standard for stateless API authentication.
Why It Matters
Unlike opaque tokens that require server-side lookup, JWT is self-contained. The server verifies the signature and reads user claims directly from the token — no database query. This enables horizontal scaling and microservice architectures.
Real-World Use
Auth0 issues JWTs for authentication. Google APIs use JWTs for service accounts. Firebase uses JWTs for user sessions. Durga Antivirus Pro uses JWTs in its dashboard API to serve 500,000+ concurrent users without session storage.
flowchart LR
A["Client"] -->|"Login"| B["Auth Server"]
B -->|"Issues JWT"| A
A -->|"API call + JWT"| C["API Server"]
C -->|"Verify signature"| D["Valid?"]
D -->|"Yes — read claims"| E["Process Request"]
D -->|"No"| F["401 Unauthorized"]
style A fill:#dbeafe,stroke:#2563eb
style B fill:#fef3c7,stroke:#d97706
style C fill:#fef3c7,stroke:#d97706
style E fill:#dcfce7,stroke:#16a34a
style F fill:#fecaca,stroke:#dc2626
What is a JWT?
A JWT is a string with three base64url-encoded parts separated by dots:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.8X4x8F0P3k
- Header — Algorithm and token type
- Payload — Claims (data about the user)
- Signature — Cryptographic verification
JWT vs Opaque Tokens
| Feature | JWT | Opaque Token |
|---|---|---|
| Self-contained | Yes — all data in token | No — server lookup required |
| Stateless | Yes | No |
| Revocable | Hard (needs blocklist) | Easy (delete from store) |
| Contains user data | Yes (claims) | No (reference only) |
| Size | Larger (includes claims) | Small (just an ID) |
| Debuggable | Decode and read claims | Must call introspection |
Code Example: Creating and Verifying a Simple JWT
import jwt
import datetime
SECRET = "my-secret-key"
# Create a JWT
payload = {
"sub": "user-123",
"name": "Alice",
"role": "admin",
"iat": datetime.datetime.utcnow(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}
token = jwt.encode(payload, SECRET, algorithm="HS256")
print(f"Token:\n{token}")
# Verify and decode
try:
decoded = jwt.decode(token, SECRET, algorithms=["HS256"])
print(f"Decoded: {decoded}")
print(f"User: {decoded['name']}, Role: {decoded['role']}")
except jwt.InvalidTokenError as e:
print(f"Invalid: {e}")
Expected output:
Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Decoded: {'sub': 'user-123', 'name': 'Alice', 'role': 'admin', ...}
User: Alice, Role: admin
Common Mistakes
1. Storing Secrets in Code
Never hardcode JWT secrets in source files. Use environment variables or a secret manager.
2. Not Using HTTPS
JWT can be intercepted if transmitted over HTTP. Always use HTTPS.
3. Including Sensitive Data in Payload
The payload is base64-encoded, not encrypted. Anyone with the token can read the claims.
4. Using JWT When Sessions Are Better
For server-rendered web apps with logout requirements, session cookies may be simpler than JWT.
5. Ignoring Token Size
JWT size grows with claims. Large JWTs increase request size. Keep claims minimal.
Practice Questions
- What three parts make up a JWT?
- What problem does JWT solve compared to opaque tokens?
- How does the server verify a JWT without a database?
- What does the
expclaim do? - Why should JWT payloads not contain secrets?
Answers:
- Header (algorithm, type), Payload (claims), Signature (verification).
- JWT is self-contained — the server validates the token without database lookup, enabling stateless auth.
- The server recomputes the signature using the shared secret (HS256) or public key (RS256). If the computed signature matches, the token is valid.
- The
exp(expiration) claim sets the token expiry time. Libraries automatically reject expired tokens. - The payload is base64-encoded, not encrypted. Anyone with the token can decode and read claims.
Challenge: Create a Python script that issues a JWT with custom claims, encodes it, decodes it to verify, and demonstrates what happens when the token expires.
FAQ
Mini Project
Create a Python script that issues a JWT, decodes it to verify, and attempts to tamper with the payload to demonstrate that signature validation catches tampering.
What's Next
Now learn about JWT Structure — a deep dive into the header, payload, and signature components.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro