Rotating refresh tokens and permission-based authorization in Spring Security
Spring Boot 4: opaque refresh tokens stored as hashes, rotation with reuse detection, HttpOnly cookies, logout, purging expired tokens; authorization with roles, authorities, permissions, a custom AuthorizationManager and @PreAuthorize.
On this page
1. The problem
The first version stores a 30-day JWT refresh token in localStorage, not in the DB: logging out just deletes it on the client. One XSS steals the token, and the attacker keeps refreshing for 30 days with no way to revoke it.
2. Key idea
A refresh token is like a numbered parking ticket: every time you take the car out you swap it for a new one. Someone returning with an old ticket means it was copied, so the lot cancels the whole chain of tickets.
| Choice | Why |
|---|---|
| Opaque (a random 256-bit string), not a JWT | only the server reads it; no temptation to "just check the signature, skip the DB" |
| Store SHA-256, not BCrypt | the token is already random, unguessable; fast lookup via a unique index |
A familyId per login |
logging out one device revokes one family |
Cookie HttpOnly; Secure; SameSite=Strict; Path=/api/v1/auth |
JS can't read it; it's only sent to refresh and logout |
Logout revokes the family and sets the cookie with Max-Age=0. Access tokens already issued live out their 15 minutes after logout; cutting them immediately needs a jti blocklist.
2.1 Permission-based authorization
Spring only has GrantedAuthority (a string). A role is an authority with the ROLE_ prefix. A permission here is a (method, path pattern) pair in the DB attached to roles, so changing permissions needs no deploy.
| Where the rule lives | Use when | Don't use when |
|---|---|---|
AuthorizationManager on (method, path) |
coarse per-endpoint rules changed at runtime | rules that depend on data ("only the order's owner") |
@PreAuthorize |
close to the business logic, can read parameters (#id) |
permissions that change often |
| A role → permission cache (Caffeine, Redis) | high load; evict when permissions change | putting permissions in the JWT: old permissions live until expiry |
3. In Java
@Transactional(noRollbackFor = InvalidRefreshTokenException.class) // family revocation commits even on 401
public Rotated rotate(String rawToken) {
Instant now = clock.instant();
RefreshToken current = tokens.findByTokenHash(sha256(rawToken)) // @Lock(PESSIMISTIC_WRITE): FOR UPDATE
.orElseThrow(() -> new InvalidRefreshTokenException("unknown refresh token"));
if (current.isRevoked()) { // an old token reused: stolen
tokens.revokeFamily(current.getFamilyId(), now);
throw new InvalidRefreshTokenException("refresh token reuse detected");
}
if (!current.getExpiresAt().isAfter(now)) throw new InvalidRefreshTokenException("expired");
current.revoke(now);
User user = current.getUser();
String next = issueInFamily(user, current.getFamilyId());
var roles = user.getRoles().stream().map(Role::getName).sorted().toList(); // read INSIDE the transaction
return new Rotated(user.getEmail(), roles, next); // a plain record, not an entity
}Reading roles after the transaction closes gives a LazyInitializationException; don't fix it with open-in-view or EAGER.
AuthorizationManager, many-to-many and the cleanup job
AuthorizationManager#authorize(Spring Security 7;checkwas removed) loads the permissions of the token's roles with one JOIN:select distinct p from Role r join r.permissions p where r.name in :roleNames, then matches the request withPathPatternParser(/api/v1/users/{id}matches/api/v1/users/42). Wire it in with.requestMatchers("/api/v1/**").access(permissionCheck).- Many-to-many Role–Permission: use a
Set, not aList(a bag makes Hibernate delete every join row and reinsert); noCascadeType.REMOVE(deleting a role mustn't delete shared permissions).PUT /roles/{id}replaces the whole list rather than appending. - A grace period of a few seconds that returns the very next token reduces real users getting kicked out when a refresh response is lost; in exchange a quick thief also gets through. SPAs should allow only one refresh request at a time.
- Purging expired tokens: a nightly
@ScheduledsingleDELETE ... WHERE expires_at < :now; ShedLock with multiple instances; batched deletes for large tables. - A frontend on another site (a different eTLD+1) won't get the cookie with
SameSite=Strict; you needNone+ a CSRF token or anOrigincheck.
4. Working with AI
Delegate to AI: the refresh-token entity and repository, refresh/logout endpoints, integration tests covering reuse and concurrency.
Check yourself:
- The refresh token is a random string; the DB stores a hash, not the token.
-
findByTokenHashhas@Lock(PESSIMISTIC_WRITE);rotatehasnoRollbackFor. - Reusing a revoked token revokes the whole family.
- The cookie is
HttpOnly,Secure,SameSite, with a narrowPath; refresh errors clear it. - A dedicated
AccessDeniedExceptionhandler keeps 403s from becoming 500s.
5. Exercises
Exercise 1: Review a rotate that "detects reuse"
AI wrote rotate with a plain @Transactional, an unlocked findByTokenHash, and the note "reusing an old token revokes the whole family". Manual testing: reusing the old token correctly gives 401, but the new token still works afterwards. Also, two tabs refreshing together both get new tokens. Why? Name tests.
Solution to Exercise 1
- The revocation doesn't commit:
InvalidRefreshTokenExceptionis aRuntimeException, so@Transactionalrolls back the family-revokingUPDATE. Fix:noRollbackFor = InvalidRefreshTokenException.class. - Both tabs win: without a row lock both read the unrevoked token. Fix:
@Lock(PESSIMISTIC_WRITE); the second request waits, then sees the token revoked. - Tests: (1) refresh R1 → R2; refresh R1 again → 401; refresh R2 → 401. (2) two threads refreshing R1 via a
CountDownLatchon a real DB: exactly one succeeds.
Exercise 2: Read a mass-logout incident
After turning on rotation, 3% of mobile users get logged out every day, mostly in weak-signal areas. Logs show Refresh token reuse detected for those very users, two requests 1–2 seconds apart from the same IP. Diagnose and propose a fix.
Solution to Exercise 2
- Diagnosis: the client sends a refresh, the server rotates, but the response is lost; the client retries with the old token, the server sees reuse and revokes the family. Not an attack: same IP, 1–2 seconds apart.
- Proposal: a grace period of a few seconds: a token just revoked by rotation and reused within that window returns the very next token (store
replaced_by) without revoking the family. Clients allow only one refresh at a time. - Trade-off: a thief using the token within those seconds also gets through; financial systems may stay strict and accept the logouts.
Summary
- A refresh token is a random string, stored as SHA-256, tied to a family per login.
- Rotate on every refresh; reusing an old token revokes the whole family.
- Lock the row when rotating;
noRollbackForso the revocation commits. - Cookie
HttpOnly; Secure; SameSite=Strictwith a narrowPath. - Roles carry the
ROLE_prefix; (method, path) permissions in the DB change without a deploy.
Further reading: RBAC, SSO and OAuth2.
Practice interview questions on this topic
- Why do we need refresh tokens, and how does rotation with reuse detection work?
- How does the Spring Security filter chain work, and why can't @RestControllerAdvice catch token errors?
- How do you implement JWT authentication and authorization in Spring Security end to end?
- What is RBAC, what are its limits, and why check permissions rather than roles?
Comments
Community rules