BBackend CourseLeroy Labs
0/0
Search the course

Refresh tokens, rotation, reuse detection & session management

Short access plus long refresh tokens, storing only hashes, rotation on every use, detecting stolen tokens via reuse, per-user session caps, device lists and "sign out other devices". Five projects show five maturity levels.

● advancedSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

Access tokens should be short-lived (5–30 minutes) so that a stolen one is useful only briefly. Users shouldn’t have to log in every 15 minutes, though, so you also issue a refresh token. It is long-lived, sent only to /auth/refresh, and exchanged for a new access token.

Rotation and reuse detection

login           -> RT1 (stored hashed, status=ACTIVE)
refresh(RT1)    -> mark RT1 USED, issue RT2           (rotation)
refresh(RT2)    -> mark RT2 USED, issue RT3
attacker uses stolen RT1 again ->  RT1 is already USED  =>  THEFT DETECTED
                                   revoke the whole token family / all user sessions

If an attacker and the real user both hold the same refresh token, whoever uses it second triggers detection, and everyone has to log in again. Without rotation, a stolen refresh token gives months of silent access.

Refresh token rotation with reuse detectionLogin issues RT1. Refreshing with RT1 marks it used and issues RT2, then RT2 is exchanged for RT3. If a stolen RT1 is presented again, the server sees an already-used token and revokes the whole session family.ClientAuth serverDB (hashes only)POST /loginsave hash(RT1) ACTIVEaccess token + RT1 cookiePOST /refresh (RT1)RT1 → USED · save RT2new access + RT2⚠ Attacker replays a stolen RT1POST /refresh (RT1 again)RT1 already USED!revoke whole family401: everyone must log in again
Whoever uses a refresh token second triggers detection. SperoTek adds a short grace window so two tabs refreshing at once aren't flagged.

Store only a hash

A refresh token is effectively a password. Store SHA-256(token), not the raw token. A fast hash is fine here, because the token is 256 bits of randomness and can’t be brute-forced, unlike human passwords.

String raw = base64url(secureRandom(32));
repo.save(new RefreshToken(user, sha256(raw), expiresAt, userAgent, ip));
setCookie("refreshToken", raw);   // only the client holds the raw value

Five maturity levels in your projects

Spring-Boot-StoreAuthController.login · /auth/refresh

Level 1. The refresh token is a stateless JWT in an HttpOnly, Secure cookie. It is not stored and not rotated, so it can’t be revoked before it expires and theft can’t be detected.

Hostel-Web-AppRefreshTokenService.rotateRefreshToken

Level 2. Stored in the DB and rotated. Reuse of a revoked token runs deleteByUser(...) and logs “CRITICAL SECURITY ALERT”, and a daily cleanup runs at midnight. The analysis found the token was stored and looked up raw, even though email/reset tokens in the same app were SHA-256 hashed. Fixed in Hostel PR #1: the entity now stores SHA-256(token), and the raw value lives only in a @Transient field long enough to set the cookie.

Report-Manager-2module/auth/application/RefreshTokenService.java · SessionController

Level 3. Hash only (jwtUtil.hashRefreshToken(raw)), with the user agent and IP recorded per session, a cap of 5 tokens per user, and reuse detection that revokes all of the user’s tokens with reason SUSPICIOUS_ACTIVITY_BREACH_DETECTED. Users get a session list (/api/auth/sessions) and revoke-others.

IR3D (Kontentt)auth/application/RefreshTokenService.java

Level 4. Hashed (secureTokenUtil.hash), rotated in place (existing.markUsed(...)), with human-readable device labels (DeviceLabelParser turns a user agent into “Chrome on Windows”), hourly cleanup, and @ActivityLogged("SESSION_REVOKED"). The WebSocket layer also rejects revoked sessions (“Session has been revoked”).

SperoTek (in dev)UserSession · SessionService · RefreshCookie · UserSessionRepository

Level 5. Server-side UserSession rows with a full policy:

  • Idle timeout of 30 minutes (15 for privileged users) and an absolute timeout of 12 hours.
  • At most 5 concurrent sessions.
  • A 60-second grace period after rotation, so two browser tabs refreshing at once don’t trigger a false theft alarm.
  • PESSIMISTIC_WRITE lock on the session row, so refresh requests run one at a time.
  • The cookie is httpOnly(true) and sameSite("Strict").

Alternatives

  • Sliding sessions (extend on activity) vs absolute expiry (SperoTek uses both).
  • OAuth 2.1 / BFF pattern: a backend-for-frontend holds the tokens, and the browser only gets a session cookie.
  • Sender-constrained tokens (DPoP, mTLS) bind a token to a client key, so a stolen token is useless elsewhere.
  • Logout. Revoke the refresh token server-side and clear the cookie with the same domain, path and SameSite attributes (Hostel’s clearAuthCookie sets maxAge 0 with matching attributes). Otherwise the browser keeps it.
  • Token cleanup jobs. Expired rows pile up, and every project schedules a cleanup.
  • Step-up re-authentication for sensitive actions (MFA lesson).

Check yourself

1. Why is SHA-256 acceptable for refresh tokens but not passwords?
2. An already-used refresh token is presented. Best response?
3. Purpose of SperoTek’s 60s grace window?