Refresh tokens and logout (the trade-offs)
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A 15-minute token forces a new login four times an hour, and a token that lasts weeks cannot be cancelled when a phone is lost. The API needs a sign-in that lasts days and can still be switched off.
Why a stateless token cannot simply be deleted
A refresh token is a long-lived token whose only job is to get new access tokens. The server stores a record of it, so unlike a JWT it can be cancelled.
A stateless token is checked with the key alone, so the server keeps no list of tokens and there is nothing to delete. ShopLite splits the job in two.
access token JWT, 15 min, checked with the key on every request, cannot be revokedrefresh token random 256-bit value, 7 days, a row in refresh_token, revoked at logoutlogin -> access token + refresh token15 min -> access token expires -> POST /auth/refresh with the refresh token -> new access token + NEW refresh token (the old one is revoked)logout -> POST /auth/logout -> the refresh token family is revoked"Logout" on the client only forgets the token; a copy someone else made keeps working until exp. For 15 minutes that is acceptable for a shop, but not for keeping a user signed in for weeks. So the access token stays short and stateless, and the refresh token carries the long-lived sign-in in a form the server stores and can revoke.
Example 5 shows this honestly: after logout the refresh token is dead, but the access token from the same login still opens /api/v1/me until it expires.
Refresh tokens stored as a hash in a refresh_token table
A token family is the group of refresh tokens that come from one login, all sharing one family id. Revoking the family cancels every token in the chain at once.
A refresh token works like a password for the next 7 days, so the database must not hold it in plain form. The code below stores only a hash of each token.
Example 1 · src/main/resources/db/migration/V5__create_refresh_token.sql
Runs in: the shoplite-api Spring Boot project
-- Refresh tokens: only a SHA-256 hash of each token is stored, never the token itself.-- Every token that comes from one login shares a family_id; reuse of an old token revokes the family.CREATE TABLE refresh_token ( refresh_token_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, token_hash CHAR(64) NOT NULL, family_id CHAR(36) NOT NULL, expires_at DATETIME NOT NULL, revoked_at DATETIME NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT uq_refresh_token_hash UNIQUE (token_hash), CONSTRAINT fk_refresh_token_user FOREIGN KEY (user_id) REFERENCES app_user (user_id) ON DELETE CASCADE);
CREATE INDEX idx_refresh_token_family ON refresh_token (family_id);... INFO ... o.f.core.internal.command.DbMigrate : Migrating schema `shoplite` to version "5 - create refresh token"
mysql> SELECT refresh_token_id, user_id, LEFT(token_hash,12) AS hash_start, LEFT(family_id,8) AS family,
-> expires_at, revoked_at FROM refresh_token; -- after one login and one refresh
refresh_token_id user_id hash_start family expires_at revoked_at
1 2 dee4a7108ff3 00927db5 2026-10-23 13:46:12 2026-10-16 13:46:15
2 2 489d5736a6cf 00927db5 2026-10-23 13:46:16 NULLWhat this code does
token_hashisCHAR(64): SHA-256 written as 64 hex characters, with aUNIQUEconstraint so one hash cannot appear twice.ON DELETE CASCADEremoves a user's refresh tokens with the account; the family index makes "revoke the whole family" fast.- The rows show rotation: token 1 was revoked at 13:46:15 when token 2 was issued, both in family
00927db5.
Example 2 · src/main/java/com/shoplite/auth/RefreshTokenService.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.auth;
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.time.Clock;import java.time.LocalDateTime;import java.util.Base64;import java.util.HexFormat;import java.util.UUID;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
/** * Long-lived refresh tokens: random strings (not JWTs) whose hashes live in the refresh_token table. * Each use swaps the token for a new one (rotation); using an old one again revokes the whole login. */@Servicepublic class RefreshTokenService {
private static final Logger log = LoggerFactory.getLogger(RefreshTokenService.class);
private final RefreshTokenRepository tokens; private final JwtProperties properties; private final Clock clock; private final SecureRandom random = new SecureRandom();
RefreshTokenService(RefreshTokenRepository tokens, JwtProperties properties, Clock clock) { this.tokens = tokens; this.properties = properties; this.clock = clock; }
/** The user id behind a refresh token that was just used, and the token that replaces it. */ public record Rotation(Integer userId, String newToken) { }
/** A new login: a new family. Returns the token itself; only its hash is saved. */ @Transactional public String issueForNewLogin(Integer userId) { return issue(userId, UUID.randomUUID().toString()); }
/** * Swaps a refresh token for a new one in the same family. noRollbackFor: when an old token is * reused, the revocation of its family must be saved even though we answer with an error. */ @Transactional(noRollbackFor = InvalidRefreshTokenException.class) public Rotation rotate(String rawToken) { LocalDateTime now = LocalDateTime.now(clock); RefreshToken current = tokens.findByTokenHash(hash(rawToken)) .orElseThrow(InvalidRefreshTokenException::new); if (current.isRevoked()) { // This token was already exchanged (or logged out). Either the client has a bug, or someone // stole it. We cannot tell who is who, so the whole login ends: both must sign in again. int revoked = tokens.revokeFamily(current.getFamilyId(), now); log.warn("Reuse of a revoked refresh token for user {}: revoked {} active token(s) of its family", current.getUserId(), revoked); throw new InvalidRefreshTokenException(); } if (current.isExpired(now)) { throw new InvalidRefreshTokenException(); } current.revoke(now); return new Rotation(current.getUserId(), issue(current.getUserId(), current.getFamilyId())); }
/** Logout: ends this login on every device that shares the family. Unknown tokens are ignored. */ @Transactional public void revoke(String rawToken) { tokens.findByTokenHash(hash(rawToken)) .ifPresent(token -> tokens.revokeFamily(token.getFamilyId(), LocalDateTime.now(clock))); }
private String issue(Integer userId, String familyId) { byte[] bytes = new byte[32]; // 256 random bits random.nextBytes(bytes); String rawToken = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); LocalDateTime expiresAt = LocalDateTime.now(clock).plus(properties.refreshTokenTtl()); tokens.save(new RefreshToken(userId, hash(rawToken), familyId, expiresAt)); return rawToken; }
/** SHA-256 is enough here: the token is 256 random bits, so there is nothing to guess. */ static String hash(String rawToken) { try { byte[] digest = MessageDigest.getInstance("SHA-256").digest(rawToken.getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(digest); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA-256 is missing from this JDK", e); } }}No main method: AuthService calls it. Example 3 shows rotation and reuse through the API.
What this code does
issuemakes 32 random bytes, saves onlyhash(raw)and returns the raw token to the caller once.rotatehandles four cases: unknown (401), revoked (reuse: revoke the family, 401), expired (401), valid (revoke it, issue the next one).- The entity and repository are small:
RefreshTokenmaps the table, andRefreshTokenRepositoryhas the lockedfindByTokenHashand a bulkrevokeFamilyupdate.
ShopLite's refresh token is not a JWT: it is 32 random bytes from SecureRandom, in Base64URL (43 characters), so there is nothing inside to read or forge. The refresh_token table, added by the Flyway migration V5, holds one row per token: the user, a SHA-256 hash, a family id, expires_at and revoked_at.
If the database leaks, hashes are useless for signing in. A fast SHA-256 is enough here, unlike for passwords, which need BCrypt, because the token has 256 random bits and there is nothing to guess. The raw token is returned once in the login response and never stored.
Refresh token rotation and reuse detection
Rotation means each refresh token works only once: using it revokes it and returns a new access token and a new refresh token in the same family.
If a refresh token is copied, the owner and the thief both hold it. Rotation lets the server notice. The commands below log in, refresh, then use the old token again.
Example 3 · Rotation and reuse detection with curl
Runs in: the shoplite-api Spring Boot project
# 1. log in: the response now has a refreshToken toocurl -s -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \ -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}'# 2. swap refresh token 1 for new tokenscurl -i -X POST http://localhost:8080/api/v1/auth/refresh -H "Content-Type: application/json" \ -d '{"refreshToken":"Olw-UZp3R4h5yifGkTn_UxXAt5KgZhtGvCgJB4OqwAU"}'# 3. someone sends refresh token 1 again (a stolen copy, or a buggy app)curl -i -X POST http://localhost:8080/api/v1/auth/refresh -H "Content-Type: application/json" \ -d '{"refreshToken":"Olw-UZp3R4h5yifGkTn_UxXAt5KgZhtGvCgJB4OqwAU"}'# 4. the real app now tries its newer refresh token 2curl -s -X POST http://localhost:8080/api/v1/auth/refresh -H "Content-Type: application/json" \ -d '{"refreshToken":"rg-JklP8sOyF4GNvadIv84T6VU6ANh1OPK5nh7tp6Qs"}'{"accessToken":"eyJraWQiOiJVVWFwcy1CaDlC...CLeQ-8","tokenType":"Bearer","expiresIn":900,"refreshToken":"Olw-UZp3R4h5yifGkTn_UxXAt5KgZhtGvCgJB4OqwAU"}
HTTP/1.1 200
Content-Type: application/json
{"accessToken":"eyJraWQiOiJVVWFwcy1CaDlC...mNn0o","tokenType":"Bearer","expiresIn":900,"refreshToken":"rg-JklP8sOyF4GNvadIv84T6VU6ANh1OPK5nh7tp6Qs"}
HTTP/1.1 401
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The refresh token is invalid or has expired. Sign in again.","instance":"/api/v1/auth/refresh"}
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The refresh token is invalid or has expired. Sign in again.","instance":"/api/v1/auth/refresh"}
Server log:
... WARN ... com.shoplite.auth.RefreshTokenService : Reuse of a revoked refresh token for user 2: revoked 1 active token(s) of its family
... WARN ... com.shoplite.auth.RefreshTokenService : Reuse of a revoked refresh token for user 2: revoked 0 active token(s) of its family
mysql> SELECT refresh_token_id, user_id, LEFT(family_id,8) AS family, revoked_at FROM refresh_token;
refresh_token_id user_id family revoked_at
1 2 00927db5 2026-10-16 13:46:15
2 2 00927db5 2026-10-16 13:46:26What this code does
- The first refresh succeeds and returns a different refresh token; the old one is now revoked.
- Sending the old token again is treated as theft: 401, and the warning says one active token of the family was revoked.
- So the newer token fails too. Whoever really owns the account logs in again with the password; the thief cannot.
Reuse detection is what rotation buys you: a revoked token should never come back, so if it does, either the app has a bug or someone copied it. The server cannot tell the thief from the owner, so it revokes the whole family and both must log in again. noRollbackFor makes sure that revocation is saved even though the request ends with a 401. The user, the roles and the enabled flag are read from the database again at each refresh, so a disabled account or a new role takes effect at the next one.
The lookup uses SELECT ... FOR UPDATE (@Lock(PESSIMISTIC_WRITE)), so two refreshes with the same token run one after the other: the second one sees a revoked token. The cost is that an app which refreshes twice at once (two tabs) logs itself out, so clients should refresh from one place.
Predict the output
What does the server do?
Read the code and pick what it prints.
Round 1 of 2
A thief sends the old token A again. What happens?
Logout by revoking the refresh token, and deny-lists
A deny-list is a table or cache of cancelled access-token ids (the jti claim), checked on every request. It closes the gap after logout, but brings back a lookup on every request.
Logging out should end the sign-in. ShopLite's logout endpoint revokes the refresh token's family and answers 204, whatever token it receives.
Example 4 · src/main/java/com/shoplite/auth/AuthService.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.auth;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.user.UserPrincipal;import com.shoplite.user.UserService;
/** Sign-in, token refresh and sign-out. */@Servicepublic class AuthService {
private static final Logger log = LoggerFactory.getLogger(AuthService.class);
private final AuthenticationManager authenticationManager; private final TokenService tokenService; private final RefreshTokenService refreshTokens; private final UserService userService;
AuthService(AuthenticationManager authenticationManager, TokenService tokenService, RefreshTokenService refreshTokens, UserService userService) { this.authenticationManager = authenticationManager; this.tokenService = tokenService; this.refreshTokens = refreshTokens; this.userService = userService; }
/** Throws an AuthenticationException (401) for a wrong e-mail, a wrong password or a disabled account. */ @Transactional public TokenResponse login(LoginRequest request) { Authentication result = authenticationManager.authenticate( UsernamePasswordAuthenticationToken.unauthenticated(request.email(), request.password())); UserPrincipal user = (UserPrincipal) result.getPrincipal(); String refreshToken = refreshTokens.issueForNewLogin(user.getId()); log.info("User {} signed in", user.getId()); return TokenResponse.bearer(tokenService.createAccessToken(user), tokenService.accessTokenSeconds(), refreshToken); }
/** * A new access token and a new refresh token for a valid refresh token. The user is read again, * so a disabled account or a changed role takes effect at the next refresh. */ @Transactional(noRollbackFor = InvalidRefreshTokenException.class) public TokenResponse refresh(RefreshRequest request) { RefreshTokenService.Rotation rotation = refreshTokens.rotate(request.refreshToken()); UserPrincipal user = userService.findPrincipal(rotation.userId()) .filter(UserPrincipal::isEnabled) .orElseThrow(InvalidRefreshTokenException::new); return TokenResponse.bearer(tokenService.createAccessToken(user), tokenService.accessTokenSeconds(), rotation.newToken()); }
/** Ends the login that this refresh token belongs to. Access tokens already issued live until exp. */ public void logout(RefreshRequest request) { refreshTokens.revoke(request.refreshToken()); }}No main method: AuthController calls it for POST /api/v1/auth/login, /refresh and /logout (Examples 3 and 5).
What this code does
- Login now creates a new family with
issueForNewLogin, andTokenResponsegains its fourth field,refreshToken. refreshreads the user again withfindPrincipaland refuses disabled accounts, so blocking a user stops their next refresh.logoutonly revokes;AuthControllermaps it to@ResponseStatus(HttpStatus.NO_CONTENT), and all three URLs are inpermitAllbecause the body carries the proof.
Example 5 · Logout, and what it does not cancel
Runs in: the shoplite-api Spring Boot project
curl -i -X POST http://localhost:8080/api/v1/auth/logout -H "Content-Type: application/json" \ -d '{"refreshToken":"8FZHPbbRtr0VUlxDj5-y1S4zXy9pI-9i8wegOg_WSGk"}'curl -s -X POST http://localhost:8080/api/v1/auth/refresh -H "Content-Type: application/json" \ -d '{"refreshToken":"8FZHPbbRtr0VUlxDj5-y1S4zXy9pI-9i8wegOg_WSGk"}'curl -s http://localhost:8080/api/v1/me -H "Authorization: Bearer $ACCESS_TOKEN" # from the same logincurl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:8080/api/v1/auth/logout \ -H "Content-Type: application/json" -d '{"refreshToken":"8FZHPbbRtr0VUlxDj5-y1S4zXy9pI-9i8wegOg_WSGk"}'HTTP/1.1 204
Date: Fri, 16 Oct 2026 08:17:40 GMT
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The refresh token is invalid or has expired. Sign in again.","instance":"/api/v1/auth/refresh"}
{"id":2,"email":"asha.rao@example.com","fullName":"Asha Rao","customerId":1,"roles":["CUSTOMER"]}
204What this code does
- Logout answers 204 with no body; the refresh token is dead at once.
- The access token from the same login still opens
/api/v1/meuntil itsexp, at most 15 minutes. That is the trade-off of stateless tokens. - A second logout with the same token is also 204: logout is safe to repeat and reveals nothing.
POST /api/v1/auth/logout takes the refresh token in the body and revokes its whole family. An unknown or already revoked token also gets 204, so the endpoint reveals nothing and a double tap on the logout button is harmless. The access token from that login still works until exp, at most 15 minutes.
A deny-list closes that gap, but it is the per-request state that JWTs were meant to avoid. It is worth it when 15 minutes of access after logout or after an account is blocked is not acceptable: banking, admin panels, a stolen admin token. For a shop's customers, short access tokens plus refresh revocation are the usual answer.
Choosing a design: short tokens, refresh tokens, or sessions
Short tokens only: simple, nothing stored, but users log in every 15 minutes. Fine for scripts, service-to-service calls and short tasks.
Access plus refresh tokens (ShopLite): short stateless checks on every request, a database row only at refresh and logout, sign-in that lasts days, real logout and reuse detection. Good for mobile apps and single-page apps talking to an API.
Sessions (the HTTP Basic and sessions module): instant logout and no token handling in the client, but state on the server and CSRF protection for cookies. Still the simplest choice for a server-rendered website on one domain, such as the admin console. Picking sessions there is not old-fashioned; it is the right tool.
Next step
Check your understanding
12 quick questions