When OAuth Refresh Tokens Live Forever: How to Force Short Expiry in Production

OAuth 2.0 refresh tokens are supposed to be long‑lived, but “forever” is a misnomer that can open a wide attack surface. A compromised refresh token gives an attacker persistent access without re‑authenticating, and if it never expires the window for damage widens. Below is a practical checklist that shows how to enforce short expiry, monitor usage, and mitigate risk without breaking the user experience.

1. Enforce Expiry at Issuance

Most IdPs expose a knob for refresh‑token lifetime. If you control the IdP, set a maximum TTL that matches your threat model.

# Example: Keycloak realm configuration
{
  "refreshTokenPolicy": "RENEW",
  "refreshTokenMaxReuse": 1,
  "refreshTokenExpiration": 86400   # 1 day
}

If you’re on a third‑party service (Auth0, Okta, etc.), use the dashboard or API to set the Refresh Token Rotation policy and the Refresh Token Expiration value. For providers that don’t have a UI, check the docs – many expose a refresh_token_expires_in parameter in the token response.

2. Rotate Tokens on Every Use

Token rotation forces the client to exchange the current refresh token for a brand‑new one on every refresh. This slims the window an attacker can use a stolen token.

POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token
refresh_token=old_token
client_id=abc123
client_secret=secret

The IdP returns a fresh refresh token and revokes the old one. Store only the latest token in a secure, HTTP‑only cookie or encrypted storage. If the client receives an invalid_grant error, force a re‑login.

3. Add Usage Auditing

Track refresh‑token usage per client, IP, and device. A sudden spike from a new IP or device should trigger an alert.

# Example: Splunk query
index=oauth_logs
action=refresh
| stats count by client_id, ip, device_id
| where count > 10

Set a threshold that balances noise and detection. For high‑value apps, consider a 3‑point rolling window: if a token is used more than N times in M minutes, revoke it.

4. Enforce Conditional Access

Use contextual factors to decide whether a refresh is allowed. For instance, block refreshes from untrusted networks or require MFA for high‑privilege scopes.

{
  "conditions": {
    "ip_range": "10.0.0.0/8",
    "mfa_required": true
  },
  "action": "allow"
}

Many IdPs support policy engines (Azure AD Conditional Access, etc.). If your stack doesn’t, implement a lightweight middleware that checks the request context before forwarding to the IdP.

5. Revoke on Suspicious Activity

If a token is used from a location that differs from its original registration, revoke it immediately.

curl -X POST \
  -H "Authorization: Bearer admin_token" \
  https://idp.example.com/admin/clients/{client_id}/revoke \
  -d '{"refresh_token":"old_token"}'

Store the original client IP and device fingerprint in your database. Compare on each refresh. If mismatched, trigger a revocation and force re‑authentication.

6. Keep Clients Updated

Clients must handle token revocation gracefully. A 401 response with invalid_grant should clear stored tokens and redirect to the login flow. Avoid silent failures that leave stale tokens in memory.

fetch('/api/data', { headers: { Authorization: `Bearer ${token}` } })
  .catch(err => {
    if (err.status === 401) {
      localStorage.removeItem('refresh_token');
      window.location.href = '/login';
    }
  });

7. Test the Flow

Automate end‑to‑end tests that:

  1. Request a refresh token.
  2. Use it to obtain an access token.
  3. Reuse the same refresh token to confirm revocation.
  4. Verify that a new refresh token is issued.
pytest tests/test_refresh_rotation.py

8. Document the Policy

Publish a clear policy that explains:

  • Refresh token lifetime (e.g., 24 h).
  • Rotation rules.
  • Revocation triggers.
  • User notification procedures.

Transparency helps developers understand the security posture and cuts down support tickets.


See also