Skip to content
notes.vinhnq.com

Search

SecuritySenior16 min read

Rotating refresh tokens and permission-based authorization in Spring Security

Review 14 cards
On this page

Spring Security for REST APIs series: 1. JWT with the resource server · 2. Refresh tokens and authorization

With a 15-minute access token, users need a way to get a new one without logging in again, and a real way to log out. This post implements rotating refresh tokens on Spring Boot 4, then permission-based authorization stored in the database. Rotation theory is in the authentication post, RBAC theory and schema in the authorization post; here is code whose tests were run.

1. Designing the refresh token in the database

Key idea: a refresh token must be revocable, so it is a DB record. Store a hash, not the raw string, and attach a familyId to know which tokens came from the same login.

@Entity
@Table(name = "refresh_tokens", indexes = @Index(name = "ix_refresh_family", columnList = "family_id"))
public class RefreshToken {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    /** SHA-256 of the raw token: a DB leak must not hand out valid tokens. */
    @Column(name = "token_hash", nullable = false, unique = true, length = 64) private String tokenHash;
    /** All tokens produced by rotation from one login share a family. */
    @Column(name = "family_id", nullable = false, length = 36) private String familyId;
    @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "user_id") private User user;
    @Column(nullable = false) private Instant expiresAt;
    private Instant revokedAt;
    // ...
}
  • Opaque, not a JWT: only the server reads a refresh token, so it needs no claims. A random string is shorter, reveals nothing, and removes the temptation to “just verify the signature and skip the DB”.
  • SHA-256, not BCrypt: the token already has 256 random bits and can’t be guessed like a password, so a fast hash is enough and can be looked up through a unique index.
  • familyId = one session on one device. Logging out one device revokes one family.

2. Rotation with reuse detection

Key idea: a valid token is revoked and a successor is issued in the same family. A revoked token showing up again means two parties hold the same token, so revoke the whole family and answer 401.

sequenceDiagram
  participant U as User
  participant A as Thief
  participant API
  U->>API: refresh with R1
  API-->>U: R2 (R1 revoked)
  A->>API: refresh with stolen R1
  API-->>A: 401, whole family revoked
  U->>API: refresh with R2
  API-->>U: 401, must log in again
@Transactional(noRollbackFor = InvalidRefreshTokenException.class)
public Rotated rotate(String rawToken) {
    Instant now = clock.instant();
    RefreshToken current = tokens.findByTokenHash(sha256(rawToken))   // SELECT ... FOR UPDATE
            .orElseThrow(() -> new InvalidRefreshTokenException("unknown refresh token"));
    if (current.isRevoked()) {
        int n = tokens.revokeFamily(current.getFamilyId(), now);
        log.warn("Refresh token reuse detected, family={} revoked={} user={}",
                current.getFamilyId(), n, current.getUser().getId());
        throw new InvalidRefreshTokenException("refresh token reuse detected");
    }
    if (!current.getExpiresAt().isAfter(now)) throw new InvalidRefreshTokenException("refresh token expired");
    current.revoke(now);
    User user = current.getUser();
    String next = issueInFamily(user, current.getFamilyId());
    var roles = user.getRoles().stream().map(r -> r.getName()).sorted().toList();
    return new Rotated(user.getEmail(), roles, next);
}

Three small details decide right from wrong:

  • @Lock(PESSIMISTIC_WRITE) on findByTokenHash: two tabs refreshing at once means the second request waits, then sees the token revoked. Without the lock both get a new token and the family forks.
  • noRollbackFor: on reuse we throw to answer 401. By default @Transactional rolls back on a RuntimeException, which would undo the family revocation UPDATE. The lab’s test asserts the family is revoked after the 401.
  • An injected Clock: tests can move time instead of Thread.sleep.

Key idea: the refresh token travels in an HttpOnly cookie with a narrow Path; the access token travels in the body. Logout revokes this device’s family and clears the cookie with Max-Age=0.

private static ResponseCookie cookie(String value, long maxAgeSeconds) {
    return ResponseCookie.from("refresh_token", value)
            .httpOnly(true).secure(true).sameSite("Strict")
            .path("/api/v1/auth")      // browser sends it only to refresh/logout, not to every API call
            .maxAge(maxAgeSeconds).build();
}

@PostMapping("/refresh")
public ResponseEntity<ApiResponse<TokenResponse>> refresh(
        @CookieValue(name = COOKIE, required = false) String cookie) {
    if (cookie == null) throw new InvalidRefreshTokenException("missing refresh token");
    RefreshTokenService.Rotated r = refreshTokens.rotate(cookie);
    // roles re-read from DB on every refresh: a role change applies within one access-token lifetime
    return withTokens(jwtService.issueAccessToken(r.email(), r.roles()), r.rawToken());
}

@PostMapping("/logout")
public ResponseEntity<Void> logout(@CookieValue(name = COOKIE, required = false) String cookie) {
    if (cookie != null) refreshTokens.revoke(cookie);
    return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", 0).toString()).build();
}
  • SameSite=Strict plus a narrow Path replaces a CSRF token for the cookie-based endpoint. If the frontend lives on an entirely different site (different eTLD+1), Strict won’t send the cookie; then you need None + a CSRF token or an Origin check.
  • The InvalidRefreshTokenException handler returns 401 and clears the cookie, so the client doesn’t loop forever with a dead token.
  • An already issued access token lives until its 15 minutes run out after logout. To cut it immediately you need a jti denylist or a per-user “token version” (ways to revoke JWTs).

4. Purging expired tokens

Key idea: expired and revoked tokens stay in the table; a nightly job deletes them with one DELETE. With several instances, lock so only one runs it.

@Scheduled(cron = "0 0 2 * * *")   // 02:00 in the server's time zone
@Transactional
public void purgeExpired() {
    int deleted = tokens.deleteExpiredBefore(clock.instant());
    log.info("Purged {} expired refresh tokens", deleted);
}

It needs @EnableScheduling on the application class. Three things a senior adds: ShedLock (or a DB lock) for multiple instances, an explicit zone on the cron, and batched deletes on a large table to avoid long locks. Covered in depth in cron jobs and deleting old data safely.

5. Roles, authorities and permissions in Spring

Key idea: Spring has a single concept, GrantedAuthority (a string). A role is an authority prefixed with ROLE_; a permission is an authority you name yourself, or, as in the lab, a (method, path) rule stored in the DB.

You write Spring stores / compares
.roles("ADMIN") authority ROLE_ADMIN
hasRole('ADMIN') compares with ROLE_ADMIN
.authorities("CREATE_USER") authority CREATE_USER
hasAuthority('CREATE_USER') exact string match

Two places to put rules:

  • URL rules in authorizeHttpRequests: coarse, centralised, run before the controller.
  • Method security with @EnableMethodSecurity + @PreAuthorize: close to the business, can read parameters (#id), runs in the bean’s proxy.

6. DB permissions with a custom AuthorizationManager

Key idea: each permission is (method, path pattern), attached to roles through permission_role. An AuthorizationManager takes the roles from the token, loads those roles’ permissions with one JOIN query, and matches them against the request.

@Override
public AuthorizationResult authorize(Supplier<? extends Authentication> authentication,
                                     RequestAuthorizationContext ctx) {
    Authentication auth = authentication.get();
    if (auth == null || !auth.isAuthenticated()) return new AuthorizationDecision(false);
    List<String> roleNames = auth.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .filter(a -> a.startsWith("ROLE_")).map(a -> a.substring(5)).toList();
    if (roleNames.isEmpty()) return new AuthorizationDecision(false);

    String method = ctx.getRequest().getMethod();
    PathContainer path = PathContainer.parsePath(ctx.getRequest().getRequestURI());
    boolean granted = permissions.findByRoleNames(roleNames).stream()
            .anyMatch(p -> p.getMethod().equalsIgnoreCase(method)
                    && PathPatternParser.defaultInstance.parse(p.getApiPath()).matches(path));
    return new AuthorizationDecision(granted);
}
@Query("select distinct p from Role r join r.permissions p where r.name in :roleNames")
List<Permission> findByRoleNames(Collection<String> roleNames);
  • Path patterns, not string equality: the permission stores /api/v1/users/{id}, the request is /api/v1/users/42. PathPatternParser matches the way Spring MVC maps controllers.
  • Wiring into the chain: .requestMatchers("/api/v1/**").access(permissionCheck).
  • Changing a role’s permissions is a data change, no redeploy, and takes effect immediately because it is looked up per request.
Role–Permission many-to-many: full replacement, Set and the owning side

PUT /roles/{id} takes permissionIds and replaces the whole list (not additive):

@Transactional
public Role replacePermissions(Long roleId, Set<Long> permissionIds) {
    Role role = roles.findWithPermissionsById(roleId)
            .orElseThrow(() -> new ResourceNotFoundException("Role", "id", roleId));
    role.replacePermissions(loadAll(permissionIds));   // clear() then addAll()
    return role;                                        // dirty checking flushes the diff at commit
}

Set<Permission> loadAll(Set<Long> ids) {
    List<Permission> found = permissions.findAllById(ids);
    if (found.size() != ids.size()) {                  // findAllById silently skips unknown ids
        // ... throw ResourceNotFoundException with the first missing id
    }
    return new HashSet<>(found);
}
  • Set, not List: with an unordered List (a bag), Hibernate deletes all of the role’s join rows and re-inserts them when you remove one element.
  • No CascadeType.REMOVE on @ManyToMany: deleting a role must never delete shared permissions.
  • The owning side is the one with @JoinTable. Deleting from the owning side makes Hibernate delete the join rows first. The source says “DELETE role → JPA clears the join table (cascade)”: true only because Role owns permission_role, and it isn’t cascade. For user_role, owned by User, deleting an assigned Role fails with a foreign key violation, unless you first remove the role from its users or refuse to delete roles in use.
  • The lab’s @DataJpaTest asserts that after a replacement the old permission still exists, only the link is gone; it calls em.flush(); em.clear() to test real SQL, not just the first-level cache.

7. Two layers: URL permission and @PreAuthorize

Key idea: the URL permission answers “may this role call this endpoint”; @PreAuthorize and the service answer rules the URL can’t express. The lab requires all three for DELETE /users/{id}.

@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<Void> delete(@PathVariable Long id, Authentication auth) {
    userService.delete(id, auth.getName());   // the service refuses self-deletion
    return ResponseEntity.noContent().build();
}
  • Role HR has the DELETE /api/v1/users/{id} permission but isn’t ADMIN → passes the filter, blocked by @PreAuthorize → 403.
  • ADMIN with the permission → 204; ADMIN deleting themselves → 400 from the business rule in the service.
  • Rules like “only users of the same company” or “never delete SUPER_ADMIN” belong in the service, because they need data. These are exactly what AI-generated code tends to miss.
@ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
void accessDenied(org.springframework.security.access.AccessDeniedException ex) {
    throw ex;   // let security answer 403 instead of falling into the catch-all 500
}

8. Tests: proving the flow works

Key idea: security flows need integration tests that run the real filter chain: 200 with permission, 403 without, 401 when an old token is replayed. The lab uses @SpringBootTest + MockMvc and a TestDataFactory that creates users with exactly the permissions a test needs.

@Test
void reusingARotatedTokenRevokesTheWholeFamily() throws Exception {
    String first = login();
    String second = mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))
            .andReturn().getResponse().getCookie("refresh_token").getValue();

    mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))   // thief replays
       .andExpect(status().isUnauthorized())
       .andExpect(jsonPath("$.detail").value("refresh token reuse detected"));

    mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", second)))  // newest token dies too
       .andExpect(status().isUnauthorized());
    assertThat(tokens.findAll()).allMatch(RefreshToken::isRevoked);
}
The other tests: 403 and 200, logout
@Test
void roleWithoutPermissionIs403() throws Exception {
    User viewer = data.user("viewer@example.dev", "secret-pass-1", "VIEWER");   // role with no permission
    mvc.perform(get("/api/v1/users/" + admin.getId())
            .header("Authorization", "Bearer " + data.accessToken(viewer, "VIEWER")))
       .andExpect(status().isForbidden())
       .andExpect(jsonPath("$.status").value(403));
}

@Test
void permissionMatchingPathPatternIs200() throws Exception {
    mvc.perform(get("/api/v1/users/" + admin.getId())
            .header("Authorization", "Bearer " + data.accessToken(admin, "ADMIN")))
       .andExpect(status().isOk())
       .andExpect(jsonPath("$.data.email").value("admin@example.dev"));
}

@Test
void logoutRevokesAndClearsCookie() throws Exception {
    String refresh = login();
    mvc.perform(post("/api/v1/auth/logout").cookie(new Cookie("refresh_token", refresh))
            .header("Authorization", "Bearer " + data.accessToken(admin, "ADMIN")))
       .andExpect(status().isNoContent())
       .andExpect(header().string("Set-Cookie", containsString("Max-Age=0")));
    mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", refresh)))
       .andExpect(status().isUnauthorized());
}

TestDataFactory.user(email, password, role, "GET /api/v1/users/{id}", ...) creates the permissions, role and user, and issues a real JWT for that user. The tests are not @Transactional: they commit like production, so both the lazy-loading bug and the effect of noRollbackFor are visible. Each test calls data.reset() in @BeforeEach.

Run results (JDK 21, Spring Boot 4.0.3, H2): mvn test ran 29 tests, 28 passed, 1 skipped (the Testcontainers test; Docker couldn’t run on this machine). They include 4 rotation/logout tests, 3 tests for 401/403/200 and 2 method-security tests. The per-request permission lookup was not load-tested, and nothing ran on a real MySQL/PostgreSQL.

Remember

  • Explain why a refresh token is a random string stored as a hash, not a JWT.
  • Draw the reuse-detection flow and name the two code details that make it correct (row lock, noRollbackFor).
  • Know why LazyInitializationException appears after a @Transactional service returns, and the right fix.
  • Tell roles, authorities and permissions apart in Spring, and where each kind of rule belongs.
  • Know the cost of a per-request DB permission lookup and how to cache it with eviction.

Interview questions

Junior

Why do we need a refresh token if we already have an access token?

So the access token can be short-lived (minutes) without users logging in constantly, and so the server has a place to revoke the session.

An access token is verified without the DB, so it can’t be revoked; the refresh token lives in the DB, so logout or blocking an account takes effect at the next refresh.

What is the difference between hasRole(‘ADMIN’) and hasAuthority(‘ADMIN’)?

hasRole('ADMIN') compares with the authority ROLE_ADMIN; hasAuthority('ADMIN') matches the exact string ADMIN.

A role is just an authority with the ROLE_ prefix. Mixing the two styles is a common source of puzzling 403s.

Mid

Why store a hash of the refresh token, and why SHA-256 rather than BCrypt?

Hashing means a DB leak doesn’t leak usable tokens; SHA-256 is enough because the token has 256 random bits and can’t be guessed like a password.

BCrypt is slow to resist guessing weak passwords; random tokens don’t need that, and a deterministic hash can be looked up through a unique index.

A @Transactional service returns an entity, the controller calls getRoles() and gets LazyInitializationException. Why, and how do you fix it?

A lazy collection can only load while the Hibernate session is open, and the session closes with the transaction; with open-in-view off, the controller has no session.

Fix it by building the data you need (a DTO/record) inside the transaction, or with a fetch join / entity graph. Don’t fix it with open-in-view or EAGER.

Why can @ExceptionHandler(Exception.class) give unauthorized users a 500?

Because @PreAuthorize throws AccessDeniedException during the controller call, the advice catches it before security does, and the catch-all returns 500.

Add a dedicated handler for AccessDeniedException (re-throw or return 403), and test the forbidden case.

Senior

Design rotating refresh tokens with reuse detection. Where is the implementation easy to get wrong?

Each refresh revokes the old token and issues a new one in the same family; a revoked token showing up again revokes the whole family. The traps are concurrency, transactions and user experience.

  • Two parallel refreshes: use a row lock or a conditional update, otherwise the family forks.
  • Throwing after revoking the family: needs noRollbackFor, otherwise the revocation rolls back.
  • Lost responses: consider a short grace period, and a single refresh in flight on the client.
  • Log reuse warnings for investigation.
You check (method, path) permissions in the DB on every request. What changes in production?

Cache role → permissions (in-process or Redis) with eviction when permissions change, measure latency, and still keep permissions out of the JWT.

Pre-compile path patterns instead of parsing them per request. Agree on an acceptable delay for permission changes. Keep data-based business rules (same company, record ownership) in the service, because URLs can’t express them.

What happens with a JPA many-to-many when you delete a Role that is assigned to users?

It depends on the owning side: if User owns user_role, deleting the Role fails with a foreign key violation; Hibernate only removes join rows when deleting from the owning side.

Remove the role from its users first (in the same transaction) or refuse to delete a role in use with a clear 409. Never put CascadeType.REMOVE on a many-to-many.

Useful phrases for interviews

  • “With rotation, every refresh token can be used exactly once.”
  • “Reuse detection revokes the whole family when an old token comes back.”
  • “The refresh token is opaque and we only store its SHA-256 hash.”
  • “A row lock serializes two parallel refreshes with the same token.”
  • “We use noRollbackFor so the family revocation commits even though we answer 401.”
  • “The cookie is HttpOnly, Secure, SameSite Strict and scoped to the auth path.”
  • “A role is just an authority with the ROLE_ prefix.”
  • “URL permissions decide who may call an endpoint; method security and the service handle rules that need data.”
  • “We evict the permission cache whenever a role changes.”
  • “Only the owning side of a many-to-many writes the join table.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.