patternMajorpending
JWT token best practices — storage, expiry, and refresh flow
Viewed 0 times
JWTrefresh tokenhttpOnly cookietoken rotationRS256access tokentoken storage
nodejspythonbrowser
Problem
JWT implementation has security issues: tokens stored in localStorage are vulnerable to XSS, long-lived tokens are dangerous if leaked, and refresh token rotation is not implemented correctly.
Solution
(1) Storage: use httpOnly, secure, sameSite=strict cookies — not localStorage (XSS vulnerable). (2) Short access token TTL: 15 minutes. Long refresh token TTL: 7-30 days. (3) Refresh flow: when access token expires, use refresh token to get new pair (access + refresh). Rotate refresh tokens on each use — invalidate the old one. (4) Token payload: include sub (user ID), exp, iat, iss. Don't include sensitive data — JWTs are encoded, not encrypted. (5) Use asymmetric signing (RS256) for microservices — public key can verify without secret. (6) Revocation: maintain a blocklist of revoked tokens (check on each request) or use short TTLs and let them expire. (7) Always validate exp, iss, and aud claims.
Why
JWTs are self-contained — once issued, they're valid until expiry unless explicitly revoked. Short-lived access tokens limit the damage window if leaked. Refresh token rotation detects token theft (reuse = compromise).
Revisions (0)
No revisions yet.