Nonce Reuse in OAuth Flows: How One Missing Counter Broke User Consent
Archi4 min read
Contents
The Broken Counter That Let Tokens Swap#
On March 12, a midsize health data portal began receiving reports of users seeing other patients’ lab results. Engineers found no database leaks or session hijacking. Instead, they traced the issue to a single line in an authentication service: a nonce generator that reset on every server restart.
The system used OAuth 2.1 with PKCE and required a cryptographically random nonce for each authorization request. But the implementation stored the nonce counter in volatile memory, not Redis, not PostgreSQL, just a local integer variable. When the service scaled to three nodes and restarted twice during a routine patch window, two nodes reused nonces from earlier sessions. That reuse allowed attackers to substitute valid ID tokens across unrelated user flows.
Why Nonce Reuse Breaks Consent Boundaries#
OAuth nonces are not optional decoration. They bind an ID token to a specific authorization request. When the same nonce appears in two separate authorization code exchanges, the OpenID Connect specification treats them as interchangeable. An attacker who intercepted one authorization code could swap it for another, and still get a valid ID token signed by the identity provider.
This is not theoretical. In this case, an internal test script had logged a valid authorization code and nonce pair during staging. That pair leaked into a shared CI artifact bucket. A developer downloaded the file, ran the code locally, and triggered a second exchange using the same nonce. The identity provider issued a new ID token, but one that carried the original user’s claims and audience restrictions. The portal accepted it because its signature and expiration were valid.
No encryption was broken. No keys were exposed. The flaw sat entirely in state management: a missing persistence layer for a single 32-byte value.
The Stack Trace Led Straight to Memory#
Forensics started with the ID token’s nonce claim. Logs showed identical base64-encoded nonces appearing in two distinct auth_time windows, separated by 87 minutes and 14 seconds. Next, engineers checked the identity provider’s audit log. It confirmed both tokens were issued with the same nonce and same client ID, but different code_challenge values. That ruled out replay attacks and pointed to deliberate reuse.
They then reviewed the portal’s nonce generation function:
go var nonceCounter uint64 = 0 func generateNonce() string { nonceCounter++ return fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%d-%s", nonceCounter, time.Now().String())))) }
The variable resets on process start. With rolling deployments and auto-scaling, three instances cycled within 90 seconds. Each started at zero. Within 4 minutes, all three generated overlapping nonces.
No external entropy source was used. No fallback to /dev/urandom. No versioned schema for nonce storage. Just sequential counting in RAM.
What the Fix Actually Required#
The engineering team deployed a two-part fix within 11 hours. First, they added Redis-backed nonce tracking with TTLs matching the authorization code lifetime (10 minutes). Second, they changed the generation logic to use crypto/rand.Read() for raw bytes, then base64-url encode, removing the counter entirely.
They also added a pre-flight check: before issuing an authorization code, the service now verifies the nonce has not been seen in the last 15 minutes. This prevents reuse even if clock skew or deployment timing creates edge cases.
Testing revealed a side effect: the old counter-based method produced nonces averaging 43 bytes. The new method averages 44 bytes due to base64-url padding. That broke one legacy mobile SDK that enforced a hard 43-character limit on the nonce parameter. The team patched the SDK and rolled out a forced update to 12,400 active devices over 48 hours.
Why This Was Not a Protocol Failure#
Some engineers argued the identity provider should reject duplicate nonces. But the OpenID Connect Core specification does not require that. Section 3.1.3.7 states only that the RP “MUST” include a nonce and “SHOULD” ensure uniqueness. The identity provider’s job is signature validation, not state enforcement. That boundary exists for good reason: scalability. Enforcing global nonce uniqueness would require cross-region coordination and add latency to every authorization flow.
The responsibility sits squarely with the relying party. And in this case, the relying party treated nonce generation as a lightweight utility, like generating a temporary filename, rather than a cryptographic binding primitive.
Lessons Beyond the Code#
This incident did not involve misconfigured CORS, forgotten CSP headers, or expired certificates. It involved a decision to avoid database writes for performance reasons. Engineers measured the Redis round-trip at 1.7 ms median. They estimated 22 extra milliseconds per authorization flow if they added a write-and-check step. So they chose local state.
That trade-off held until the system scaled past one node. Then it failed, not catastrophically, but precisely: only when two users happened to authorize within the same 10-minute window after a restart, and only if one had a leaked code from staging.
The root cause was not complexity. It was omission: no test case for multi-node nonce collision, no alert on duplicate nonce submissions, no requirement in the architecture decision record to persist nonces across restarts.
Privacy failures like this rarely begin with malicious actors. They begin with assumptions about scale, uptime, and isolation that hold true until they don’t. Here, the assumption was that one process equals one instance. When Kubernetes spun up replacements faster than the nonce counter could drift, the assumption cracked, and user consent boundaries dissolved with it.
More articles