SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

JWT

A signed pass with your details inside, which a server can check without a database.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A JWT (JSON Web Token, said β€œjot”) is a small, signed pass. It carries facts about the user, such as who they are and when the pass expires.

  • It has 3 parts joined by dots: header.payload.signature.
  • The server checks the signature, so it does not need to look in a database on every request.
  • The payload is encoded, not encrypted. Anyone can read it. Never put secrets in it.

02Concept: What is it?

A JWT is a string like xxxxx.yyyyy.zzzzz. Each part is JSON written in base64url, a way to make text safe for URLs and headers.

The three parts of a JWT
🏷️Header{"alg":"HS256","typ":"JWT"}
→↓.
πŸ“¦Payload (claims){"sub":"asha","role":"user","exp":…}
→↓.
✍️Signaturemade with a secret key
How it is signed The facts The proof
Change one letter in the payload and the signature no longer matches.
PartWhat it holdsExample claims
HeaderThe token type and the signing algorithmalg, typ, kid (key id)
PayloadClaims: facts about the user and the tokensub (who), iss (who issued), aud (for whom), iat (issued at), exp (expires), role
SignatureA seal over header and payload, made with a keyHMAC-SHA256(header.payload, secret)
⚠️Signed is not secret
Base64 is just a format. Paste any JWT into a decoder and you can read it. The signature only proves that nobody changed it.

03Real-Life Example

🍡The Festival Wristband
At a music festival you show your ticket once. The staff put a wristband on you with the day and the zone printed on it. After that, every guard just looks at the band. They do not call the ticket office. A fake band is spotted by the special seal that only the festival can print.
Festival wristband
JWT
Showing the ticket once
Logging in once
Wristband
The token
Text printed on it (day, zone)
Payload claims
Special seal
Signature
Guards check the seal, not the office
Server verifies the signature, no database call
Band is valid for one day
exp claim (expiry)
Cannot cancel a band already on a wrist
Hard to revoke a JWT before it expires

04Why Do We Need It?

⚑No lookup per request
A server can check the pass alone, so it is fast and easy to scale.
🧩Works across servers
Any server with the key can verify it. No shared session store.
πŸ”ŒGreat for microservices
One service issues it. Many services verify it.
πŸ“±Fits mobile and APIs
Sent in a header. No cookies needed.
🌐A standard
Libraries exist in every language.
A JWT lets a server trust a user without asking anyone. The price: you cannot easily take the pass back.

05Where Do We Use It?

πŸ”‘API access tokens
Sent as β€œAuthorization: Bearer <token>”.
πŸͺͺOpenID Connect ID tokens
The login layer on top of OAuth uses a JWT to say who logged in.
πŸ”ŒService to service
A gateway passes the user's identity to services behind it.
🧭Single sign-on
A signed proof is handed from the identity provider to the app.
πŸ“§One-time links
β€œVerify your email” links, short-lived and signed.

Typical request path

πŸ“±App
→↓Bearer <JWT>
πŸšͺAPI gatewayverifies signature
→↓user id, role
πŸ–₯️Orders
πŸ–₯️Profile

06Types / Parts / How It Works

How the signature is made

Symmetric (HS256)
One shared secret
  • The same secret signs and verifies
  • Fast and simple
  • Every service that verifies also holds the secret, so it could forge tokens
  • Good for one app or a small trusted group
Asymmetric (RS256, ES256)
Private key signs, public key verifies
  • Only the issuer holds the private key
  • Anyone can verify with the public key
  • Better for many services and third parties
  • Public keys are shared in a JWKS endpoint (general idea)

Two kinds of tokens that often go together

Access tokenRefresh token
JobCall the APIGet a new access token
LifeShort: minutes (for example 5 to 15)Long: days or weeks
Sent toEvery API callOnly the auth server
If stolenUseful only until it expiresDangerous. Store safely, rotate it, and be able to revoke it

Where the browser keeps it

PlaceGoodRisk
HttpOnly + Secure + SameSite cookieJavaScript cannot read it, so XSS cannot steal itNeeds CSRF care (SameSite helps)
localStorage or sessionStorageEasy to useAny XSS bug can read it and steal the token
In memory onlyHard for others to stealLost on page reload (pair with a refresh cookie)
VisualizerBuild a token, then tamper with itChange the name, role or life. Then press the hacker button and watch the signature break.
Role
The token the server receives

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3MDAwMDAwMDAsImV4cCI6MTcwMDAwMDkwMH0.ZTQzMjk2NGMyZTQzYjM3NTg1YWZlMjBhMjIyMDQ1MzE

● header● payload● signature (toy)
Header
How it is signed
{
 "alg": "HS256",
 "typ": "JWT"
}
Payload
The claims. Anyone can read this.
{
 "sub": "asha",
 "role": "user",
 "iat": 1700000000,
 "exp": 1700000900
}
Signature (toy)
Made with a secret key only the server knows
toyHash(header.payload + secret)
Teaching toy only. Real JWTs use HMAC-SHA256 or RSA / ECDSA.
Signature
Match
Expiry
Fresh
15 min life
Server says
200
βœ… Valid. The server trusts it: user β€œasha”, role β€œuser”. It never had to look in a database.

07How to Use It / Steps / Implementation

Issue and verify

  1. 1
    User logs in
    The server checks the password (and MFA).
  2. 2
    Server builds the payload
    sub, role, iat, exp. Keep it small. Use a short exp.
  3. 3
    Server signs it
    Use a well-known library and a strong key (long, random, kept secret).
  4. 4
    Client stores and sends it
    In a header: Authorization: Bearer <token>.
  5. 5
    Each server verifies
    Check the signature, check exp, and check iss and aud. Fix the allowed algorithm on the server.
  6. 6
    Refresh
    When the access token expires, use the refresh token to get a new one.

What to check on every request

CheckWhy
Signature is validNobody changed the token
alg is the one you expectNever accept β€œalg: none” or let the token pick its own algorithm
exp is in the futureThe token has not expired (allow a tiny clock difference)
iss (issuer) is yoursIt came from a source you trust
aud (audience) is this APIIt was meant for this service, not another one

08Key Terms to Know

TermMeaning in easy words
JWTJSON Web Token: a signed token made of header, payload and signature
ClaimOne fact in the payload, like sub or role
subSubject: who the token is about (user id)
iss / audIssuer (who made it) and audience (who it is for)
iat / expIssued at / expires at (Unix times in seconds)
base64urlA way to write bytes as URL-safe text. It is not encryption
HMACA keyed hash. Used for HS256 signatures
Bearer tokenWhoever holds it can use it
JWKSA published list of public keys used to verify tokens
RevocationCancelling a token before it expires
JWEA different format that encrypts the content (rarely needed)

09Pros, Cons and Trade-offs

βœ… Pros
  • Stateless: no session store needed
  • Fast verification
  • Works across many servers and services
  • Standard and widely supported
  • Carries useful claims for the next service
⚠️ Cons
  • Hard to revoke before expiry
  • Bigger than a session id (sent on every request)
  • Payload is readable by anyone
  • Easy to misuse (wrong algorithm, no expiry, secrets inside)
  • Stale roles: if a user's role changes, old tokens still say the old one

Trade-offs

ChoiceWe gainWe lose
Very short expiry (5 min)A stolen token dies fastMore refresh calls
Keep a revocation listCan cancel tokensYou are back to a lookup, which is a bit like sessions
Put more claims in the tokenFewer database callsBigger token and staler data
Asymmetric signingVerifiers cannot forge tokensSlower and key management is harder

10Common Problems and Mistakes

Common mistakes

  1. Putting secrets in the payload. Passwords, card numbers and private data do not belong there. It is readable.
  2. Accepting alg: none, or trusting the token's own alg. Fix the algorithm on the server. This is a famous attack.
  3. A weak or leaked signing secret. Anyone who knows it can make admin tokens.
  4. No expiry, or a very long one. A stolen token works for ever.
  5. Skipping iss and aud checks. A token meant for another service may get accepted.
  6. Storing it in localStorage on a site that may have XSS bugs.
  7. Using JWT where a plain session would do. For one normal website, a server session is often simpler and easier to revoke.
πŸ•³οΈRevocation gap
User is banned, but the token still works until exp. Use short life, or a small deny list.
πŸ§“Stale claims
Role changed at noon. The old token still says the old role until it expires.
πŸ“Token bloat
Too many claims make every request heavier.
πŸ”Refresh token theft
Rotate refresh tokens and spot reuse.

11Real-World Examples

πŸ”Login with Google, Microsoft and others
OpenID Connect gives the app an ID token which is a JWT.
☁️Cloud identity services
Issue access tokens in JWT form for their APIs.
πŸšͺAPI gateways
Verify the JWT once, then pass the user id to internal services.
🧩Microservices
Every service can verify a token on its own.
πŸ“²Mobile apps
Store a short access token and a refresh token in secure device storage.
πŸ“Note
General ideas. Each company has its own rules for token life and storage.
Access token and refresh token
πŸ“±App
→↓API call + access token
πŸ–₯️API
→↓401 expired
πŸ“±App
πŸ“±App
→↓refresh token
πŸ”Auth server
→↓new access token
🎟️New token
The access token is short. The refresh token quietly gets a new one.

12Related Topics to Read Next

Session vs Token Based Auth→

JWT is the most common self-contained token.

OAuth / OAuth2β†’

OAuth access tokens are often JWTs.

Authentication vs Authorization→

A JWT carries the result of authentication and the roles for authorization.

Single Sign-On (SSO)β†’

SSO hands a signed proof, often a JWT, to each app.

Checksums→

A signature is like a checksum that an attacker cannot fake without the key.

HTTP / HTTPS→

Tokens must only travel over HTTPS.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a signed token: header.payload.signature.
  • βœ”Encoded, not encrypted: anyone can read the payload.
  • βœ”Verify: signature, alg (fixed), exp, iss, aud.
  • βœ”Use short expiry plus a refresh token.
  • βœ”Weak spot: revocation and stale claims.
  • βœ”HS256: shared secret. RS256 / ES256: private signs, public verifies.
  • βœ”Store it: HttpOnly Secure SameSite cookie, or memory. Avoid localStorage.
  • βœ”One line: β€œA JWT is a tamper-proof note the server hands you and trusts when you bring it back.”
← Previous
Session vs Token Based Auth
Next β†’
OAuth / OAuth2