Backend / REST APIs / 02_jwt_auth.md

JWT authentication for REST APIs

Updated 3 interview angles 1 min read source

JWT authentication for REST APIs

A JWT is a signed token the client sends on every request (Authorization: Bearer <token>); the API verifies the signature and the claims instead of looking up a session. That makes verification local to each service, and makes revocation hard: a valid token stays valid until it expires.

http
GET /v1/orders HTTP/1.1
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImsxIn0.eyJzdWIiOiI0MiJ9.<signature>
python
claims = jwt.decode(token, public_key, algorithms=["RS256"],
                    audience="orders-api", issuer="https://auth.example.com")
user_id = claims["sub"]            # no session lookup needed to trust it

The mechanics live in the authentication notes, not here:

Interview angle 3

  • “Why use a JWT over a session?” - stateless verification: any service can validate the signature without a shared session store, which suits distributed systems. The cost is that you can’t revoke one before expiry.
  • “How do you handle revocation then?” - short-lived access tokens with longer refresh tokens, plus a denylist keyed on token id for immediate revocation. Accepting the trade explicitly is better than pretending JWTs are revocable.
  • “What are the classic JWT mistakes?” - not verifying the algorithm (accepting alg: none or an HMAC-signed token where RSA was expected), skipping audience and expiry checks, putting sensitive data in a payload that’s merely base64-encoded, and storing tokens in localStorage.