What is Refresh Token Reuse Detection?

What is Refresh Token Reuse Detection?

Rotation swaps the key every time it's used. Reuse detection is the alarm that goes off the moment someone tries the old, already-swapped-out key anyway.

Imagine a vault that not only changes its combination every time it’s opened, but also keeps a precise memory of every combination that’s ever been retired. If someone ever tries dialing in one of those old, dead combinations, the vault doesn’t just quietly refuse — it treats that specific attempt as proof that something has gone seriously wrong, because nobody with legitimate access should ever be holding a combination that’s already been replaced. Refresh Token Reuse Detection is exactly this alarm system inside Keycloak: the specific logic that recognizes when an already-superseded refresh token is presented again, and decides how seriously to respond. This guide focuses squarely on that detection mechanism itself — what counts as “reuse,” how Keycloak tells a harmless retry apart from a genuine red flag, what happens the instant reuse is caught, and how real teams tune and monitor this defense correctly. No prior background in token systems is assumed.

1Core Concepts

Reuse detection only makes sense once you understand what makes a refresh token “used up” in the first place — a concept that depends entirely on rotation being enabled.

What does “reuse” actually mean?

When refresh token rotation is enabled, every time a refresh token is successfully used to obtain a new access token, Keycloak also issues a brand-new refresh token and marks the one just used as superseded — no longer the current, valid token for that session. Reuse is simply the event of someone presenting that superseded token again, after it’s already been replaced. Under normal, correct client behavior, this should never happen — a well-behaved application always uses the newest token it was given, never an older one that’s already been swapped out.

Why does reuse happening at all matter so much?

If reuse only ever happened by innocent accident, it wouldn’t be worth building dedicated detection around. But there’s a specific, realistic scenario where it happens for a genuinely serious reason: an attacker has stolen a copy of a refresh token. If both the legitimate client and the attacker now hold a copy of the same token, whichever one uses it first triggers rotation and gets the new one — and the other party, still holding the now-superseded original, will trigger reuse detection the moment they try to use it. Reuse detection turns this specific, otherwise invisible race into a loud, unmistakable signal.

Analogy

Picture two people who both, unknowingly, have a copy of the same hotel room key after one was secretly duplicated. The moment either person uses their key to enter the room, the hotel’s electronic lock automatically deactivates that specific key code and issues a fresh one to whoever just walked in. If the other person — holding the now-dead duplicate — tries their key next, the door simply won’t open, and the hotel’s security desk gets an alert: “a deactivated key was just attempted.” That alert doesn’t tell the hotel which of the two people is the legitimate guest and which is the intruder — it only tells them something is clearly wrong.

Why is detecting reuse different from just preventing it?

Rotation itself already prevents an old token from working again — that part is simple rejection. Reuse detection goes a step further: it specifically recognizes this particular kind of rejection as meaningfully different from an ordinary expired or invalid token, and treats it as a signal worth acting on, typically by protectively shutting down the entire underlying session rather than just declining that one request.

i
Where you’d meet this

Any security team investigating a suspected account compromise, any application wanting an early warning sign of token theft rather than discovering it much later through other means, and any deployment with rotation enabled for its public clients relies on reuse detection as a core part of its defense.

Key vocabulary, explained simply

Term

Superseded Token

A refresh token that was valid but has already been replaced by a newer one through rotation, and should never legitimately be presented again.

Term

Reuse Event

The specific occurrence of a superseded token being presented to Keycloak’s token endpoint after it’s already been retired.

Term

Grace Period

A brief tolerance window during which a very recently superseded token may still be accepted, to absorb harmless timing issues without treating every one as an attack.

Term

Protective Session Revocation

Keycloak’s typical response to detected reuse — ending the entire underlying session as a precaution, affecting both a potential attacker and the legitimate user.

Term

False Positive

A reuse detection event triggered by a harmless cause (like a network retry) rather than genuine token theft.

Term

Token Family / Chain

The full sequence of refresh tokens issued one after another, through repeated rotation, all tracing back to a single original login.

2Architecture & Components

Reuse detection is built directly into Keycloak’s session and token-tracking machinery — it doesn’t need a separate system, but it does depend on a few specific pieces working together correctly.
graph TB
    SS[Session Store] --> CUR["Current Valid
Refresh Token Reference"] TE[Token Endpoint] -->|presented token| CMP{Matches current
valid reference?} CMP -->|yes| ROT[Rotate: issue new token,
update reference] CMP -->|no, but within grace period| GRACE[Accept under
grace tolerance] CMP -->|no, outside grace period| DETECT[Reuse Detected] DETECT --> RESP[Protective Response:
revoke session, log event]
FIG 1 — The session store’s single “current valid token” reference is what makes reuse detectable

Component breakdown

Component

Session Store’s Token Reference

Each session record keeps track of exactly one currently valid refresh token; any other token presented against that session is, by definition, no longer current.

Component

Comparison Logic at the Token Endpoint

The specific code path that checks an incoming refresh token against the session’s recorded current value, distinguishing a match, a within-grace-period near-match, and a genuine reuse case.

Component

Grace Period Configuration

A tunable setting controlling how much timing tolerance is allowed before a superseded token triggers full reuse detection rather than being quietly accepted.

Component

Event Logging for Reuse

Keycloak’s event system records reuse-detection occurrences, making them visible for later review or, when forwarded through a custom event listener, real-time alerting.

Where this is configured in the admin console

Reuse detection isn’t a separate toggle from rotation itself — it’s an automatic behavior of Keycloak’s token endpoint once rotation is enabled. The relevant tunable setting administrators actually configure is the grace period, typically found alongside other token and session settings under a realm or client’s advanced configuration, controlling how strictly or leniently near-simultaneous refresh attempts are treated.

A common real setup

A company monitoring its Keycloak deployment configures a custom event listener specifically watching for reuse-detection events, forwarding each one immediately to a security alerting channel. Rather than waiting to notice a pattern through periodic log review, the security team receives a near-instant notification the moment any user’s session shows this specific, high-confidence signal of possible token theft.

Why is a single “current valid token” reference enough to make this work?

Because Keycloak only ever considers one refresh token, per session, as currently valid at any moment, any other token presented against that session is automatically distinguishable as either the legitimate next-in-line replacement or something that’s already been superseded. This simple, single-pointer design is what makes reuse detection reliable without requiring Keycloak to maintain a complex history of every token ever issued — it only needs to know what’s current right now.

3Internal Working

The internal decision Keycloak makes on every refresh request boils down to a precise comparison, followed by one of three distinct outcomes depending on exactly how that comparison turns out.

The three possible outcomes of a refresh attempt

When a refresh token arrives at Keycloak’s token endpoint, exactly one of three things happens. First, if the token matches the session’s current valid reference, rotation proceeds normally — a new access and refresh token are issued, and the reference is updated. Second, if the token doesn’t match but falls within the configured grace period (meaning it was only very recently superseded), it may still be accepted, treated as a harmless, delayed duplicate of a legitimate request. Third, if the token doesn’t match and falls outside the grace period, this is treated as genuine reuse — a clear, high-confidence signal that something is wrong.

Why the grace period exists as a middle ground

Real network conditions occasionally cause a client to send what looks like two refresh requests very close together — for example, a slow response triggers an automatic retry, even though the original request actually succeeded moments earlier. Without any tolerance at all, this ordinary, harmless situation would trigger the same severe response as genuine theft. The grace period exists specifically to absorb this narrow category of legitimate near-simultaneous requests, without meaningfully weakening protection against a genuinely delayed, malicious reuse attempt.

“Reuse detection isn’t asking ‘is this token valid?’ — rotation already answers that. It’s asking a sharper question: ‘why is someone presenting a token that’s already been replaced?'”

What happens the instant reuse is detected

Once Keycloak determines a presented token is genuinely reused — outside any grace tolerance — its typical, protective response is to revoke the entire underlying session, not just reject that one request. This is a deliberate, conservative choice: because Keycloak cannot reliably tell, from the reuse event alone, whether the party presenting the old token is the legitimate user or an attacker, ending the whole session forces everyone involved to re-authenticate from scratch, cutting off whatever access an attacker might otherwise have continued to hold through their own copy of a still-live session.

!
Gotcha

Because the protective response typically ends the whole session, a single detected reuse event — even one eventually judged to be a false positive — still results in the legitimate user being logged out and needing to sign in again, which is an intentional trade-off favoring caution over convenience.

Step-by-step: what happens from a stolen token to a triggered alarm

1

Token copied by an attacker

Through some compromise, an attacker obtains a copy of a currently valid refresh token, unbeknownst to the legitimate user.

2

One party uses the token first

Either the legitimate client or the attacker uses the shared token, triggering normal rotation and receiving a new one.

3

Session reference updated

Keycloak updates the session’s current valid token reference to this newly issued one.

4

The other party attempts to use the same old token

Whoever didn’t get to it first still holds the now-superseded original and eventually tries to use it.

5

Reuse detected outside the grace period

Keycloak recognizes this token no longer matches the current reference and has aged past the tolerance window.

6

Session revoked and event logged

The entire session is ended as a precaution, and the reuse event is recorded for review or alerting.

4Data Flow & Lifecycle

Tracing exactly which party ends up affected by a reuse-triggered session revocation clarifies why this mechanism, while occasionally inconvenient, is deliberately designed to favor safety over precision.
sequenceDiagram
    participant Legit as Legitimate Client
    participant KC as Keycloak
    participant Attacker

    Note over Attacker: Has stolen a copy of
Refresh Token A Legit->>KC: Uses Refresh Token A first KC-->>Legit: Issues Refresh Token B (A now superseded) Attacker->>KC: Attempts to use Refresh Token A KC->>KC: Detects reuse - A no longer current KC-->>Attacker: Rejected KC->>KC: Revokes entire session as precaution Legit->>KC: Later tries to use Refresh Token B KC-->>Legit: Rejected - session already revoked, must re-login
FIG 2 — Even the legitimate client, who acted correctly, ends up needing to log in again once reuse is detected

Notice the outcome for the legitimate client in that diagram — they did everything right, used the newest token they had, and still end up needing to log in again. This is the direct cost of the protective response’s inherent uncertainty: Keycloak cannot tell, from the reuse event alone, which of the two parties holding copies of the token was the legitimate one, so it treats both equally and ends the session for everyone, prioritizing closing off the attacker’s access over sparing the legitimate user a minor inconvenience.

The lifecycle of a detection event, from trigger to resolution

A

Triggered

A superseded token is presented outside the grace period, immediately flagged internally as reuse.

B

Responded to

The session is revoked, and any connected applications are notified through normal session-termination mechanisms.

C

Logged

The event is recorded in Keycloak’s event system, available for review or forwarding through a custom event listener.

D

Investigated (ideally)

A security team or automated system reviews the event, especially if it’s part of a pattern, to determine whether it reflects genuine theft or a benign anomaly.

E

Resolved

The legitimate user simply logs in again; if genuine theft is confirmed, further action (credential reset, broader investigation) may follow.

i
Worth noting

A single, isolated reuse-detection event for one user is far less conclusive on its own than a pattern — several occurrences across accounts in a short window, or a cluster of them tied to one specific IP range, tells a much more confident story than any single event viewed in isolation.

5Advantages, Disadvantages & Trade-offs

Reuse detection converts an otherwise invisible theft scenario into a loud, actionable signal — but that same loudness means it occasionally inconveniences people who did nothing wrong.

Advantages

  • Turns token theft from a silent, undetectable event into a specific, high-confidence security signal
  • Requires no additional infrastructure — it’s a natural consequence of rotation already being in place
  • Provides a precise, forensically useful timestamp and context for when suspicious activity actually occurred
  • Automatically limits an attacker’s continued access by ending the session the moment detection fires

Disadvantages & Trade-offs

  • Cannot distinguish which party — legitimate user or attacker — actually triggered the underlying theft, so both are equally affected
  • A single event, viewed alone, doesn’t tell you whether it reflects genuine malicious activity or an edge-case false positive
  • Poorly tuned grace periods can produce either too many false alarms or too wide a window for genuine attackers to slip through
  • Provides no protection against theft scenarios where only one party ever ends up using the stolen token (for example, if the legitimate client never refreshes again before the attacker does)
Analogy

A smoke detector doesn’t tell you whether the smoke came from a genuine fire or from burnt toast — it just tells you, reliably and immediately, that something is producing smoke, leaving you to investigate and respond appropriately. Reuse detection plays exactly this role for refresh tokens: an immediate, unambiguous signal, but one that still requires human or automated judgment about what to do next.

6Security

Reuse detection is one of the more valuable, low-cost security signals available in a Keycloak deployment — but only if it’s actually watched and responded to, not just silently logged and forgotten.

Treating detection events as genuine incidents, not routine noise

The single most important security practice around reuse detection is simply making sure the events it generates are actually seen by someone, or something, capable of acting on them. A detection event sitting unread in a log file provides essentially none of the protective value it’s capable of offering — the real security benefit comes specifically from timely awareness and response.

SEC-12Recommended
Context

Reuse-detection events are often generated correctly by Keycloak but left buried in general event logs that nobody actively reviews in real time, especially in organizations without a dedicated security monitoring practice.

Decision

Route reuse-detection events specifically to an active alerting channel — a security monitoring system, a dedicated notification, or at minimum a distinctly flagged log category — rather than leaving them mixed anonymously into general event volume.

Consequence

Genuine token-theft attempts are noticed and can be investigated promptly, rather than being discovered much later, if at all, through unrelated means.

Correlating reuse events with other signals

A single reuse-detection event is a strong but not conclusive signal on its own. Correlating it with other available context — the IP address or location associated with each side of the reuse attempt, whether it coincides with other suspicious activity on the same account, or whether similar events are happening across multiple unrelated accounts at once — helps distinguish an isolated, likely-benign edge case from a genuine, active attack pattern worth immediate escalation.

!
Common mistake

Responding to every single reuse-detection event identically, regardless of context or frequency, either by over-alerting on isolated, likely-harmless edge cases or by under-responding to what’s actually a clear, repeated attack pattern across several accounts.

What reuse detection does not protect against

It’s worth being precise about the limits here: reuse detection only fires when a superseded token is presented again — it says nothing about a scenario where an attacker steals a token and simply uses it once, successfully, before the legitimate client ever gets a chance to. In that specific case, from Keycloak’s perspective, the attacker’s use looks like an entirely normal, successful rotation, with no reuse ever technically occurring. This is why reuse detection is one layer of defense, not a complete solution to token theft on its own.

7Monitoring, Logging & Metrics

Because reuse detection exists specifically to generate a security signal, how that signal is monitored and interpreted determines whether the whole mechanism delivers real protective value or just sits quietly unused.
1
reuse event is a strong signal on its own, worth reviewing individually
3
or more clustered events across accounts is a pattern worth immediate escalation
0
protective value gained from events that are logged but never actually reviewed
Metric

Raw reuse-detection event count

The most basic metric — simply tracking how many reuse events occur over time, providing a baseline against which unusual spikes can be measured.

Metric

Events per unique account

Distinguishing a single account experiencing repeated reuse events (a strong signal of targeted compromise) from a low, evenly distributed background rate across many accounts (more consistent with occasional benign edge cases).

Metric

Geographic or IP correlation

Checking whether the two “sides” of a reuse event originate from meaningfully different locations or networks, which strengthens the case for genuine theft over an internal client-side bug.

Metric

Time-to-investigation

Tracking how quickly a security team actually reviews and responds to a flagged reuse event, since the protective value of detection depends heavily on how promptly it’s acted upon.

A practical monitoring habit

Security teams often configure an alerting rule specifically for any single user account experiencing more than one reuse-detection event within a short time window, since a repeated pattern against the same account is a much stronger and more actionable signal than any single isolated occurrence, and deserves faster, more direct escalation than routine log review alone would provide.

8Design Patterns & Anti-patterns

Teams that get real, ongoing value from reuse detection tend to build a handful of consistent supporting practices around it, and commonly stumble by treating it as a passive, set-and-forget feature.

Proven patterns

Pattern

Dedicated alerting pipeline

Forward reuse-detection events specifically into an active security monitoring or alerting system, distinct from general application logs, ensuring they’re seen promptly.

Pattern

Pattern-based escalation thresholds

Define clear rules for when a reuse event warrants immediate escalation (such as repeated occurrences on one account) versus routine, lower-priority review.

Pattern

User-facing transparency

When a session is revoked due to detected reuse, provide the affected user with a clear, calm explanation on their next login, rather than a confusing, unexplained forced logout.

Pattern

Regular grace-period review

Periodically revisit the configured grace period against real observed retry patterns, adjusting it deliberately rather than leaving an untested default in place indefinitely.

Anti-patterns to avoid

Anti-pattern

  • Enabling rotation and reuse detection but never actually reviewing or alerting on the events it generates
  • Treating every reuse event as equally urgent, without distinguishing an isolated occurrence from a repeated, targeted pattern
  • Assuming reuse detection alone fully solves token theft, without complementary controls like short access token lifetimes or secure storage
  • Leaving the grace period at an untested default without validating it against actual client retry behavior

Instead, do this

  • Build an active monitoring and alerting path specifically for reuse-detection events
  • Establish clear thresholds distinguishing routine review from urgent escalation
  • Treat reuse detection as one layer within a broader, complementary token security strategy
  • Validate and periodically revisit the grace period against real-world client behavior

9Best Practices & Common Mistakes

Extracting real, ongoing value from reuse detection comes down to disciplined monitoring habits and a clear, tested plan for what happens the moment an event actually fires.

Best practices

1

Document a clear response playbook

Define, ahead of time, exactly what a security team should do the moment a reuse-detection event fires, rather than improvising a response during an actual incident.

2

Distinguish isolated events from patterns explicitly

Build monitoring logic that specifically flags repeated events on the same account or across correlated accounts as higher priority than scattered, one-off occurrences.

3

Test detection behavior deliberately

Simulate a controlled reuse scenario in a non-production environment to confirm the detection and response actually behave as expected before relying on it in production.

4

Keep users informed, not alarmed

Design the user-facing experience of a reuse-triggered logout to be clear and reassuring, avoiding language that causes unnecessary panic over what may well be a benign, resolved situation.

Common mistakes

!
Mistake

Assuming reuse detection is “on” and therefore the organization is automatically protected, without verifying that anyone actually monitors or responds to the events it generates.

!
Mistake

Conflating reuse detection with rotation itself, and assuming that simply enabling rotation automatically provides active security monitoring, when the detection events still require deliberate handling to deliver real value.

!
Mistake

Reacting to a single, isolated reuse event with an overly aggressive, disruptive response (like broadly locking an account) without first checking whether it’s part of a genuine pattern or a likely, harmless one-off.

10Real-world & Industry Examples

Reuse detection provides genuine, practical value across any industry where refresh tokens are in wide use and token theft is a realistic, meaningful risk.
Industry

Financial services fraud teams

Banking platforms treat reuse-detection events as a high-priority signal fed directly into fraud investigation workflows, given the potential severity of a compromised financial account.

Industry

Consumer platform security operations

Large consumer applications use aggregated reuse-detection data to identify broader campaigns — such as a compromised third-party library affecting many users simultaneously — rather than only investigating events one account at a time.

Industry

Enterprise security incident response

Corporate security teams incorporate reuse-detection events into their broader incident-response tooling, correlating them with other signals like unusual login locations or device changes.

Industry

Bug bounty and security research programs

Organizations running responsible disclosure programs sometimes discover reuse-detection anomalies during authorized security testing, using the findings to validate that their token security controls behave as intended under simulated attack conditions.

A representative scenario

A consumer application’s security team noticed, through their reuse-detection alerting pipeline, a cluster of events occurring across several dozen unrelated user accounts within the same short time window, all originating from a small set of unfamiliar IP addresses. Investigation revealed a coordinated credential-stuffing campaign where attackers had somehow obtained a batch of stolen refresh tokens from an unrelated data breach and were attempting to use them simultaneously. Because reuse detection had immediately flagged and revoked each affected session the moment the legitimate token holders next refreshed, the team was able to identify and respond to the broader campaign within hours, rather than discovering the compromise only after more significant damage had occurred.

11FAQ

Q1Does reuse detection require anything beyond enabling rotation?
The detection logic itself is an automatic consequence of rotation being enabled. What typically requires extra setup is making the resulting events actually visible and actionable, such as through a custom event listener forwarding them to a monitoring system.
Q2Can reuse detection tell me whether it was the attacker or the legitimate user who triggered it?
Not directly. The detection event itself only confirms that a superseded token was presented again — determining which party is legitimate usually requires additional context, like IP addresses or correlated activity.
Q3Why does the legitimate user also get logged out when reuse is detected?
Because Keycloak cannot reliably distinguish the legitimate user from an attacker at the moment of detection, its typical response revokes the entire session as a precaution, affecting both parties equally rather than risking leaving an attacker’s access intact.
Q4Is a single reuse-detection event always a sign of an attack?
Not necessarily — a poorly tuned grace period or an unusual but legitimate network retry can occasionally trigger a false positive, which is why patterns across accounts or repeated events on one account carry much stronger evidentiary weight than any single isolated occurrence.
Q5Does reuse detection catch every kind of refresh token theft?
No. It specifically catches cases where a superseded token is presented again — if an attacker uses a stolen token successfully before the legitimate client ever gets the chance to, that specific use looks like a normal, undetected rotation from Keycloak’s perspective.
Q6Where can I see reuse-detection events?
They appear in Keycloak’s standard event logging system, and can also be forwarded in real time to an external monitoring or alerting system through a custom event listener, for more immediate visibility.

12Summary and Key Takeaways

Key Takeaways

  • Refresh Token Reuse Detection recognizes when an already-superseded refresh token is presented again, treating it as a strong signal of possible token theft.
  • It relies directly on refresh token rotation being enabled, since “reuse” is only meaningful once a token has actually been replaced by a newer one.
  • A configured grace period distinguishes harmless, near-simultaneous retries from genuine, delayed reuse, balancing false positives against real protection.
  • Detected reuse typically triggers protective session revocation, affecting both a potential attacker and the legitimate user, since Keycloak cannot reliably distinguish between them at that moment.
  • The real security value of reuse detection depends entirely on the resulting events being actively monitored and responded to, not just silently logged.
  • A pattern of reuse events — repeated on one account, or clustered across many — carries far more evidentiary weight than any single isolated occurrence.
  • Reuse detection has real limits: it cannot identify which party is legitimate, and it doesn’t catch a theft scenario where the attacker simply uses a stolen token first, without any later reuse ever occurring.
  • It works best as one layer in a broader token security strategy, alongside short token lifetimes, secure storage, and other complementary protections.