Refresh Tokens
Access tokens should expire quickly.
Introduction
Access tokens should expire quickly. When they do, clients use a longer-lived refresh token to obtain a new access token without re-entering credentials.
Refresh tokens are not JWTs-by-requirement. Many Orders deployments store an opaque random token (hashed) in the database, bind it to a user and device family, and rotate it on every use.
Rotation + reuse detection matters: if a stolen refresh token is used after the legitimate client already rotated, revoke the entire family.
Keep access tokens in memory where possible; treat refresh tokens as high-value secrets — httpOnly Secure cookies for browsers, secure storage on mobile.
Purpose of this lesson
Design rotating refresh tokens so Orders clients renew short-lived JWT access tokens safely.
Understanding the topic
Short access + rotating refresh = UX without long-lived bearers.
- Access token: minutes; authorizes API calls.
- Refresh token: days; only accepted at the token endpoint.
- Rotation: issue a new refresh on each successful refresh call.
- Reuse detection: presenting an old refresh after rotation signals theft.
- Revocation: logout and password change invalidate the family.
Step-by-step explanation
- On login, persist a hashed refresh token with user id, expiry, and family id.
- Return access JWT + refresh token (body or cookie — pick one model).
- Implement
POST /api/auth/refreshthat validates, rotates, and returns a new pair. - On logout, delete or mark revoked all tokens in the family.
Syntax reference
Happy-path refresh flow.
Client Auth (/api/auth) Orders API| login | ||----------------------->| || access + refresh | ||<-----------------------| || API + Bearer access | ||-------------------------------------------------->|| ... access expired ... || POST /refresh (refresh) ||----------------------->| || new access + refresh | ||<-----------------------| |
Informative example
Opaque refresh record and rotate sketch.
public record RefreshSession(String familyId,String tokenHash,String userId,Instant expiresAt,boolean revoked) {}@Servicepublic class RefreshService {private final RefreshSessionRepository sessions;private final JwtIssuer jwtIssuer;private final PasswordEncoder hasher; // or dedicated token hasherpublic TokenPair refresh(String presentedRaw) {String hash = sha256(presentedRaw);RefreshSession current = sessions.findByTokenHash(hash).orElseThrow(() -> new BadCredentialsException("invalid_refresh"));if (current.revoked() || current.expiresAt().isBefore(Instant.now())) {sessions.revokeFamily(current.familyId());throw new BadCredentialsException("invalid_refresh");}sessions.revoke(current.tokenHash());String newRaw = randomToken();sessions.save(new RefreshSession(current.familyId(), sha256(newRaw),current.userId(), Instant.now().plus(7, ChronoUnit.DAYS), false));String access = jwtIssuer.issueAccessToken(current.userId(), List.of("USER"));return new TokenPair(access, newRaw);}}
Real-world use
TechLearningPRO mobile users stay signed in for a week, but access JWTs last fifteen minutes. Refresh rotation lets the app renew quietly. When a refresh token leaked from a backup, reuse detection revoked the family and forced a clean login — containing the blast radius.
Security implications
Refresh tokens are long-lived credentials.
- TLS only; never log raw refresh values.
- Reuse detection should revoke the whole family.
- Password change and logout must invalidate outstanding refresh sessions.
Best practices
- Hash refresh tokens at rest; treat them like passwords.
- Bind to device/family ids for targeted revocation.
- Prefer httpOnly + Secure + SameSite cookies for browser refresh when the architecture allows.
Common mistakes
- Storing refresh tokens in plaintext in the database.
- Never rotating — stolen refresh works until hard expiry.
- Sending refresh tokens to every API host instead of only the auth token endpoint.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy not make access tokens last a week?+
Answer
2IntermediateQuestionWhat is refresh rotation?+
Answer
3IntermediateQuestionOpaque refresh vs JWT refresh?+
Answer
Hands-on exercise
Lab. Implement login + refresh + logout for Orders. Refresh once successfully, then replay the old refresh token and confirm the family is revoked.
Summary
Refresh tokens keep Orders clients signed in without long-lived bearer access tokens. Next: structuring permissions with RBAC.