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
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.
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.
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
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.
Reuse Event
The specific occurrence of a superseded token being presented to Keycloak’s token endpoint after it’s already been retired.
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.
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.
False Positive
A reuse detection event triggered by a harmless cause (like a network retry) rather than genuine token theft.
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
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]
Component breakdown
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.
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.
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.
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 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.
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.
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
Token copied by an attacker
Through some compromise, an attacker obtains a copy of a currently valid refresh token, unbeknownst to the legitimate user.
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.
Session reference updated
Keycloak updates the session’s current valid token reference to this newly issued one.
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.
Reuse detected outside the grace period
Keycloak recognizes this token no longer matches the current reference and has aged past the tolerance window.
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
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
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
Triggered
A superseded token is presented outside the grace period, immediately flagged internally as reuse.
Responded to
The session is revoked, and any connected applications are notified through normal session-termination mechanisms.
Logged
The event is recorded in Keycloak’s event system, available for review or forwarding through a custom event listener.
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.
Resolved
The legitimate user simply logs in again; if genuine theft is confirmed, further action (credential reset, broader investigation) may follow.
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
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)
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
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.
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.
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
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.
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).
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.
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
Proven patterns
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-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.
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.
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
Best practices
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.
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.
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.
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
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.
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.
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
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.
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.
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.
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
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.