Refresh Token Replay: Why Your OAuth Session Survives Long After Logout

Your OAuth access token lives for five minutes. That’s by design — short-lived, easy to discard. But the refresh token? That one can survive for days, weeks, or indefinitely depending on your provider.

If your app doesn’t rotate refresh tokens on every use, an attacker who intercepts one gains a persistent session — and logout doesn’t kill it.

This isn’t a new idea. It’s a pattern I’ve hit in bug bounties, client audits, and my own self-hosted apps. Every time it shows up, it’s the same root cause: the app treats the refresh token as stateless.

How Refresh Tokens Work (and Where They Break)

The intended flow

1. User authenticates → IDP returns access token + refresh token
2. App stores refresh token securely (httpOnly cookie or secret store)
3. Access token expires → app sends refresh token to /token endpoint
4. IDP validates refresh token → returns new access token + new refresh token (rotation)
5. Old refresh token is invalidated (one-time use)

Rotation is the key word. A properly rotated refresh token is a one-time key. After use, the old one dies. Intercept it, use it once, and it’s gone.

The broken flow

Many apps (including some major providers) implement this:

1. User authenticates → app gets refresh token RT-ABC123
2. Access token expires → app sends RT-ABC123 to /token
3. IDP returns new access token + SAME refresh token RT-ABC123
4. RT-ABC123 is still valid for another 30 days

The refresh token is treated like a session cookie — stateless, reusable. Intercept it once, replay it forever.

Real-World Replay Scenarios

Scenario 1: Network sniffing (public Wi-Fi, MITM)

The user authenticates on a coffee shop Wi-Fi. Their refresh token passes through a proxy. The attacker stores RT-ABC123. Three days later, they send it to /token and get a fresh access token for the user’s account.

Why it works: The refresh token never changes. Logout only invalidates the access token — the refresh token sitting in the attacker’s hands is still valid.

Scenario 2: Log file leak

The app logs the full /token response for debugging:

{"access_token": "eyJ...", "refresh_token": "RT-ABC123", "expires_in": 3600}

The log file is readable by a junior dev, a monitoring tool, or an S3 bucket. Attacker grabs RT-ABC123. Still valid for the refresh token’s lifetime.

Scenario 3: CORS misconfiguration

The app’s /token endpoint accepts POST from any origin. Attacker’s site sends:

fetch('https://app.example.com/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: 'grant_type=refresh_token&refresh_token=RT-ABC123'
})

IDP returns new access + refresh tokens. Attacker now has a valid session.

Scenario 4: Logout doesn’t kill the refresh token

User clicks logout. App sends RT-ABC123 to /revoke. If the app doesn’t also send it to the IDP’s revoke endpoint, the token lives on. Even if it does, a replayed refresh token before revoke still gets a new pair.

Proof of Concept

Here’s a minimal Python script that demonstrates refresh token replay against a typical OAuth 2.0 token endpoint:

"""Refresh token replay demo — works against any OAuth 2.0 /token endpoint."""

import requests
import time
import json

# Target IDP (replace with your test instance)
TOKEN_ENDPOINT = "https://idp.example.com/oauth2/token"
REFRESH_TOKEN = "RT-ABC123"  # Intercepted from first login

def refresh_token(rt, client_id, client_secret):
    """Send refresh token to /token endpoint. Returns JSON response."""
    resp = requests.post(TOKEN_ENDPOINT, data={
        "grant_type": "refresh_token",
        "refresh_token": rt,
        "client_id": client_id,
        "client_secret": client_secret,
    }, timeout=10)
    resp.raise_for_status()
    return resp.json()

# Simulate attacker replaying the same intercepted refresh token
print("[+] First replay — attacker gets session")
result = refresh_token(REFRESH_TOKEN, "my-app", "secret")
print(f"    access_token: {result['access_token'][:40]}...")
print(f"    refresh_token: {result['refresh_token']}")

# Simulate user logging out (access token revoked, but refresh token lives)
time.sleep(2)

print("[+] Second replay — 30 seconds later, same RT still works")
result2 = refresh_token(REFRESH_TOKEN, "my-app", "secret")
print(f"    access_token: {result2['access_token'][:40]}...")
print(f"    refresh_token: {result2['refresh_token']}")

# The refresh token is the same — it was never rotated
assert result["refresh_token"] == result2["refresh_token"], "Token should be identical in non-rotating impl"
print("[!] Token was NOT rotated — replay attack successful")

Run it against your app’s token endpoint. If the refresh token is identical after replay, you’re vulnerable.

Rotation vs. No-Rotation: How to Check

Quick test

  1. Log in and capture the refresh token (RT-Original)
  2. Wait for the access token to expire (or use it once and let it expire)
  3. Trigger a refresh and capture the new refresh token (RT-New)
  4. Try using RT-Original again

If RT-Original works → no rotation → replay vulnerable. If RT-Original returns invalid_grant → rotation active → good.

What to look for in the codebase

# BROKEN: Same token returned
def refresh(token):
    new_access = get_new_access_token(token)
    return new_access, token  # <-- token is unchanged

# FIXED: Rotate the token
def refresh(token):
    new_access, new_token = get_new_access_token_and_rotate(token)
    revoke_old(token)  # invalidate the old one
    return new_access, new_token

The rotation check is in the IDP’s /token handler. For self-hosted apps (Authentik, Keycloak, Ory Hydra), look at the refresh token’s token_rotation or rotation config. For managed providers:

ProviderRotation behavior
Auth0Yes, by default (configurable)
KeycloakYes, Refresh Token Policy: Rotating (default)
Ory HydraYes, by default
AWS CognitoNo, refresh token is static unless Pre sign-up lambda rotates
Azure AD (Entra ID)No, refresh token is static (but has separate RT and RT Refresh)
OktaNo by default, yes with refresh_token_rotation policy

The Fix

1. Enable rotation everywhere

For self-hosted IDPs, set refresh token rotation on by default. For managed providers, enable it where available. For those that don’t rotate natively (AWS Cognito, Azure AD), implement it at the app level:

# App-level rotation for non-rotating IDPs
def refresh_with_app_rotation(refresh_token):
    # IDP returns same refresh token
    response = idp.refresh(refresh_token)
    
    # App generates its own wrapping token
    new_wrapped = rotate_token(refresh_token)  # e.g., hash, increment counter
    store_wrapped_token(new_wrapped)
    
    return response["access_token"], new_wrapped

2. Revoke old refresh tokens on logout

def logout(user_id):
    user_refresh_tokens = get_active_refresh_tokens(user_id)
    for rt in user_refresh_tokens:
        idp.revoke(rt)  # Send to IDP revoke endpoint
    clear_app_storage(user_id)

3. Bind refresh tokens to a fingerprint

Add a client fingerprint (TLS JA3 hash, user-agent + IP combo) to the refresh token metadata. On refresh, validate the fingerprint matches. This kills replay from a different network:

def refresh_with_fingerprint(refresh_token, expected_fp):
    stored_fp = get_token_fingerprint(refresh_token)
    if stored_fp != expected_fp:
        raise TokenReplayError("Fingerprint mismatch — possible replay")
    return idp.refresh(refresh_token)

4. Set a maximum refresh token lifetime

Don’t let refresh tokens live forever. 7-30 days is typical. After that, force re-authentication. For sensitive apps, 1-7 days.

What About Refresh Token Sets?

Azure AD and some providers use a two-tier refresh token system:

  • Refresh Token (RT): Rotates on every use. Short-lived (typically 1 hour sliding window).
  • Refresh Token Refresh (RT Refresh): Static. Lives until manually revoked. Used to generate new RTs.

This limits the replay window significantly. An intercepted RT is only useful for ~1 hour. The RT Refresh token is only exposed when the app re-authenticates or after a long inactivity period.

Not all providers implement this. Check your IDP’s docs.

Lessons Learned

Refresh tokens are the persistent session. Treat them like keys, not cookies. They should rotate, expire, and be revocable.

Logout is not a security boundary. It’s a UX action. If your refresh token doesn’t die on logout (sent to the IDP), the session lives on.

Rotation is not optional. It’s the difference between a replay token that works once and one that works forever.

Check your IDP’s default. Many managed providers rotate by default. Others (Cognito, Azure AD) don’t. Assume no rotation until proven otherwise.

Further Reading