How do you use JWTs safely (expiry, rotation, revocation, scopes)?
JWTs are a standard building block for modern authentication and authorization in scalable architecture. They give you stateless identity, fast validation, and simple integration across microservices. But because JWTs are self contained, they can easily become unsafe without the right controls on expiry, rotation, revocation, and scopes. This guide explains how to use JWTs safely in both real systems and system design interview settings.
Why it Matters
JWTs appear in many system design interview questions because they touch identity, distributed systems, and security. With the right design, JWTs let every backend service validate user identity locally without depending on shared session storage. This helps you scale horizontally, reduce latency, and support many device types.
At the same time, mistakes such as long expiry, no revocation plan, or putting sensitive data inside the token can create serious vulnerabilities. Interviewers expect you to demonstrate that you understand these trade offs and can design safe token based authentication for large systems.
How it Works Step by Step
Step 1. Use access tokens and refresh tokens separately
A safe JWT design uses two types of tokens.
-
Access token.
- A short lived JWT used on every API request.
- Validated by microservices through signature and claims checks.
-
Refresh token.
- A longer lived token used only to request new access tokens.
- Stored securely and tracked server side for rotation and revocation.
This separation keeps API calls stateless and fast while still giving you control over long term sessions.
Step 2. Set safe expiry times
Expiry is your first defense.
- Access tokens expire in minutes. often around five to fifteen minutes.
- Refresh tokens expire in days or weeks. but with better storage and checks.
Important rules.
- Always validate the
expclaim. - Keep access tokens short lived to limit the impact of theft.
- Add a small clock skew margin if needed for distributed systems.
Short expiry reduces risk because even if an attacker steals an access token, it stops working quickly.
Step 3. Implement refresh token rotation
Rotation means each refresh token can be used only once.
A typical rotation flow.
-
User logs in and receives
- A short lived access token
- A refresh token recorded in the database
-
Client calls the refresh endpoint before access token expiry
-
Server validates the refresh token
-
Server issues
- A new access token
- A new refresh token
-
Server marks the old refresh token as used so replay is detected
Rotation stops attackers from silently reusing stolen refresh tokens because replay immediately triggers detection.
Step 4. Build revocation into your design
Because JWTs are stateless, revocation requires additional logic.
Common revocation patterns.
-
Server side refresh token store.
- Keep refresh tokens and revoke them by updating their status.
-
User or session versioning.
- Store a version number in the user record.
- Include it inside refresh tokens.
- Increment version on password reset or suspicious activity.
- Tokens with old versions become invalid.
-
Short lived blocklist for critical access tokens.
- Useful for high risk operations.
- Kept small to maintain scalability.
Most systems rely on short expiry for access tokens and explicit revocation only for refresh tokens.
Step 5. Use scopes and claims with least privilege
Put only essential information inside the JWT.
Safe scope design.
- Scopes describe allowed actions at a high level. for example
read_profile,write_profile,stream_video. - Avoid embedding complex permission models inside the token.
- Combine JWT scopes with server side authorization for fine grained control.
This keeps tokens small and reduces the need to reissue them when permissions change.
Step 6. Validate and store tokens correctly
Core validation rules.
- Always check signature, issuer, audience, and expiry.
- Use asymmetric algorithms such as RS256 or ES256.
- Do not store sensitive data in the payload.
Client storage rules.
- Use HttpOnly secure cookies in browsers.
- Use secure device storage on mobile clients.
- Always transmit tokens over HTTPS.
These practices reduce opportunities for token theft and impersonation attacks.
Real World Example
Imagine a streaming platform similar to Netflix.
-
User signs in on a device. Auth service issues
- Short lived access token with scopes such as
stream_video - Refresh token stored in a server side table and delivered through a secure channel
- Short lived access token with scopes such as
-
Each API request sends the access token to the API gateway for signature and expiry validation.
-
When the access token is about to expire, the client sends a refresh request.
- Server validates the refresh token against its database record
- Issues new tokens and rotates the old refresh token
-
User clicks log out from all devices.
- Server revokes all refresh tokens linked to that user
- Increments user wide version number so older tokens no longer work
This pattern scales across many devices and microservices while giving strong security guarantees.
Common Pitfalls or Trade offs
-
Long lived access tokens
- If stolen, attackers have full access for days or weeks.
-
Storing tokens in browser local storage
- Vulnerable to cross site scripts. HttpOnly cookies are safer.
-
Putting too much information inside the JWT
- Makes tokens heavy and forces frequent re issuance as permissions change.
-
No strategy for revocation
- Cannot force logout or end compromised sessions.
-
Using symmetric signing keys everywhere
- If one microservice is compromised, attacker can issue new tokens.
Trade off summary. JWTs give you scale and speed, but you must layer expiry, rotation, and revocation to stay safe.
Interview Tip
A commonly asked question.
Design authentication for a system with many microservices. How will you use JWT access tokens while still allowing logout, permission changes, and minimal damage from stolen tokens
A strong answer covers short expiry, refresh token rotation, revocation using a database or version strategy, and secure client storage.
Key Takeaways
- Access tokens should be short lived and refresh tokens long lived but well protected.
- Refresh token rotation detects theft and prevents replay.
- You need explicit revocation strategies because JWTs are stateless.
- Scopes should be simple and coarse, with detailed permissions handled server side.
- Validate and store tokens securely to prevent misuse.
Table of Comparison
| Approach | Benefits | Drawbacks | Best use cases |
|---|---|---|---|
| Short lived JWT access tokens with rotated refresh tokens | Scales well for distributed systems, simple validation, low latency | Requires refresh token storage, revocation logic, slightly more client complexity | Web apps, mobile apps, microservice backends |
| Opaque session identifiers stored server side | Easy revocation and permission updates, full server control | Needs shared session store, more latency and cost at scale | Monoliths, internal dashboards, low traffic apps |
| Long lived JWT access tokens with no refresh token | Very simple for clients | Unsafe, hard to revoke, large blast radius when stolen | Prototyping or low risk temporary tools |
Further learning
To go deeper into how authentication fits into scalable architecture and distributed systems, explore these system design courses.
-
Learn real world authentication flows in Grokking the System Design Interview
-
Build strong fundamentals around stateless services, gateways, and access control in Grokking System Design Fundamentals
-
Understand multi region traffic, microservices at scale, and identity propagation in Grokking Scalable Systems for Interviews
GET YOUR FREE
Coding Questions Catalog
$197

$78
$78