JWT Complete Guide: Structure, Security & Best Practices
Anowar Hossen Farvez
Software Engineer
Everything you need to know about JSON Web Tokens in one place. From basic structure to security best practices and real-world use cases — this comprehensive guide covers it all.
What is JWT?
JWT (JSON Web Token) is a way to securely transfer information between two parties. Think of it like a sealed envelope:
The contents are visible to anyone who looks, but the seal proves it hasn't been tampered with since it was created.
When you decode a JWT, you can read its contents. But only someone with the secret key can create a valid signature. If anyone modifies the data, the signature won't match, and the token will be rejected.
Why is JWT So Popular?
Stateless Authentication
No server-side session storage required. The server doesn't need to remember anything — all the information it needs is in the token itself.
Secure
Uses cryptographic signatures to prevent data tampering. You can trust that if a token validates, the data inside hasn't been modified.
Flexible
Can store user IDs, roles, permissions, and any other claims you need. You define what goes in the payload.
JWT Structure
Every JWT consists of three parts, separated by dots:
xxxxx.yyyyy.zzzzz
header.payload.signature
1. Header
Contains the token type (JWT) and the signing algorithm being used (e.g., HS256, RS256).
2. Payload
The actual data storage — user information like user ID, roles, permissions, and expiration time. These pieces of data are called "claims."
3. Signature
A cryptographic signature created using the header, payload, and a secret key. This is what makes the token tamper-proof.
Common Claims in the Payload
- iss (Issuer) — Who created the token
- sub (Subject) — Who the token is about (usually user ID)
- aud (Audience) — Who the token is intended for
- exp (Expiration) — When the token expires
- iat (Issued At) — When the token was created
- nbf (Not Before) — Token is not valid before this time
A Visual Example
Header
{ "alg": "HS256", "typ": "JWT" }
Payload
{ "sub": "1234567890", "name": "Farvez", "role": "admin", "exp": 1716239022 }
Signature
HMACSHA256(base64(header) + "." + base64(payload), secret)
JWT Creation Process
- Create the Header — Specify the algorithm and token type.
- Create the Payload — Add user data (claims) and an expiration time.
- Combine Header and Payload — Base64 encode both and join them with a dot.
- Generate the Signature — Use your secret key to sign the combined header and payload.
- Return the JWT — The final token is:
header.payload.signature
JWT Refresh Mechanism
Access tokens should be short-lived for security. Refresh tokens allow users to get new access tokens without re-authenticating:
Refresh Flow
- Verify the refresh token's validity
- Check if it's not expired
- Issue a new JWT using the existing user data
- Optionally rotate the refresh token
Keep access tokens short-lived (15 minutes to 1 hour) and refresh tokens longer-lived (days to weeks) but stored securely.
Security Validation
When a JWT arrives at your server, here's how to validate it:
- Split the JWT into header, payload, and signature
- Recreate the expected signature using the header and payload
- Compare — if signatures match and token is not expired, it's valid
Common JWT Mistakes
1. Storing Sensitive Data in JWT
Never store confidential information in JWT. It's visible to anyone who can access it. JWTs are Base64 encoded, not encrypted.
2. Ignoring Expiration
Always set expiration times (exp claim). A token without expiration can be abused forever if compromised.
3. Insecure Storage
Avoid localStorage! Use secure HTTP-only cookies instead. localStorage is vulnerable to XSS attacks.
4. Using Weak Algorithms
Employ strong signing methods like HS256 or RS256. Never use none algorithm in production.
Real-World Use Cases
- Secure API Authentication — Stateless user verification without server sessions.
- Single Sign-On (SSO) — Multi-application access with a single login.
- Microservices Security — Service-to-service communication without central session stores.
Security Best Practices Checklist
- Enforce HTTPS — Never transmit JWTs over unencrypted connections
- Set brief expiration — Short-lived tokens limit damage from theft
- Use strong algorithms — HS256 or RS256, never "none"
- Secure storage — Use HTTP-only cookies, not localStorage
- Rotate secret keys — Regularly update your signing keys
- Validate all claims — Check issuer, audience, and expiration
- Keep payloads small — Only include necessary claims
- Implement token revocation — Have a strategy for invalidating tokens
Conclusion
Understanding JWT mechanics is crucial for implementing secure authentication. Remember: JWTs are not encrypted by default — they're signed. Anyone can read the payload, but only the server with the secret key can create valid signatures.
By avoiding common mistakes and following best practices, you can build secure, scalable authentication systems that serve your users well.