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.
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.
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
AuthController.login · /auth/refreshLevel 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.
RefreshTokenService.rotateRefreshTokenLevel 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.
module/auth/application/RefreshTokenService.java · SessionControllerLevel 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.
auth/application/RefreshTokenService.javaLevel 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”).
UserSession · SessionService · RefreshCookie · UserSessionRepositoryLevel 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_WRITElock on the session row, so refresh requests run one at a time.- The cookie is
httpOnly(true)andsameSite("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.
Related concepts you must know
- Logout. Revoke the refresh token server-side and clear the cookie with the same domain, path and SameSite attributes (Hostel’s
clearAuthCookiesets 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).