Dev.to Security 🔐 Cybersecurity 👁 0 📖 3 min read

Refresh token rotation with reuse detection in Spring Boot 3.5 (and the concurrency trap)

Every Spring Boot project I start needs the same thing: login, sessions, password reset, roles, and a way to log a user out of a device they no longer have. It's maybe two weeks of work, it's never the interesting part,

Every Spring Boot project I start needs the same thing: login, sessions, password reset, roles, and a way to log a user out of a device they no longer have. It's maybe two weeks of work, it's never the interesting part, and it's very easy to get subtly wrong.

This is the design I settled on, with the parts that actually cost me debugging time.

The shape: short-lived JWT + opaque rotating refresh token

  • Access token — JWT, HS256, 15 minutes. Validated in a filter; the request never touches the database.
  • Refresh token — a random 256-bit value, 7 days, returned to the client. The server stores only a SHA-256 hash of it.

That last decision is the one worth arguing about. Hashing means you can't look a token up by value — you hash the presented token and match the hash. In exchange, a leaked refresh_tokens table contains no usable credentials. For a table that only ever needs equality lookups, that trade is easy to take.

Rotation and reuse detection

Each refresh token row belongs to a family: one login on one device.

  1. Client presents refresh token R.
  2. Server hashes it, finds the row, checks family status.
  3. Row is marked consumed, a successor S is issued in the same family.
  4. Client gets a new access token and S.

Now the useful property: if a consumed token appears again, one of two things happened — the client is replaying a token it shouldn't have, or someone stole it. Either way the family is revoked and every token in that login stops working. The user re-authenticates; the attacker's copy is dead.

That's the whole theft-detection story, and it runs on the database you already have. No Redis, no token blacklist to keep warm.

The trap: parallel refreshes

Two tabs, both with an expired access token, both fire a refresh at the same time. The first rotates R → S. The second presents R, which is now consumed. Reuse detection fires, the family dies, and the user gets thrown out mid-work.

Two fixes, and you need both:

Client side — a single-flight refresh in the axios interceptor: the first 401 starts a refresh, every other request awaits the same promise, then all of them retry with the new token.

let refreshing: Promise<string> | null = null;

api.interceptors.response.use(undefined, async (error) => {
  const original = error.config;
  if (error.response?.status !== 401 || original._retried) throw error;
  original._retried = true;

  refreshing ??= refreshAccessToken().finally(() => { refreshing = null; });
  const token = await refreshing;
  original.headers.Authorization = `Bearer ${token}`;
  return api(original);
});

Server side — a short grace window: a just-consumed token presented again within a few seconds returns the same successor instead of triggering reuse revocation. Without this, a mobile network retry alone can log someone out.

Things I'd tell my past self

  • Never log the raw refresh token, even at debug level. Once you hash on write, a raw token in a log is the only copy that exists.
  • Expired rows need a scheduled cleanup; otherwise the table becomes a growth chart of your users' sessions.
  • Distinguish revocation reasons in the audit log: user logout, device revoked, password change, and reuse detection are different events, and support questions depend on telling them apart.
  • Rate-limit the auth endpoints. Password reset and email verification are cheap to abuse.

Around the core

The rest is ordinary work: BCrypt, account enable/disable, USER/ADMIN roles, admin user search with pagination, per-device session list, security audit log with IP and user agent, Flyway migrations for MySQL 8 (H2 for local), RFC 9457 problem responses, OpenAPI 3 + Swagger UI, Actuator probes, and JUnit 5 + MockMvc integration tests that walk register → verify → login → rotate → replay → revoke.

Why I packaged it

I got tired of writing this per project, so I turned it into a starter kit with the React frontend that consumes it (protected routes, role guards, the interceptor above). It's a paid product, which is why it's linked here — https://hwmich5.gumroad.com/l/springlaunch — $29, one developer, commercial license.

If you just want the backend, the dev profile runs with no Docker and no database install:

cd backend && ./mvnw spring-boot:run
# [email protected] / Demo1234!, [email protected] / Admin1234!

The rotation model is the part I'd like criticism on. If your approach handles the concurrent-refresh race better, I'd like to read it.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.