Prompt
How do I prevent replay attacks on APIs?
Latest observation
Oct 29, 2026
OpenAI APIWeb search: off
To prevent replay attacks on APIs, you want to make each request unique, time-bound, and verifiable, so an intercepted request can’t simply be resent later.
Core defenses
1) Use TLS everywhere
- Always require HTTPS/TLS.
- This doesn’t fully stop replay by itself, but it prevents passive interception and is the foundation.
2) Add a nonce
- Include a single-use random value (
nonce) in each request. - The server stores seen nonces for a short period and rejects duplicates.
- Best for authenticated requests or signed payloads.
Example:
POST /transfer
Authorization: Signature ...
X-Nonce: 8f3a9c2e-...
3) Add a timestamp and enforce a short expiry window
- Include a request timestamp, and reject requests outside a small window, e.g. 30–300 seconds.
- This limits how long a captured request is usable.
Example:
X-Timestamp: 1730000000
4) Sign the request contents
- Use an HMAC or digital signature over:
- HTTP method
- path
- query string
- body
- timestamp
- nonce
- The server verifies the signature before processing.
This ensures an attacker can’t modify a replayed request without invalidating it.
5) Bind the request to a token or client key
- If using API keys, bearer tokens, or OAuth access tokens, don’t rely on them alone.
- Prefer proof-of-possession approaches where the client must prove it possesses a private key or secret for each request.
Examples:
- OAuth DPoP
- mTLS
- Signed requests with shared secret
6) Use idempotency keys for unsafe operations
- For actions like payments or order creation, require an idempotency key.
- This doesn’t stop replay in the cryptographic sense, but it prevents repeated side effects if the same request is resent.
Example:
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
7) Maintain replay caches
- Store recently seen
(nonce, client_id)or request hashes for the validity window. - Reject duplicates.
- Use a fast store like Redis with TTL.
Best-practice request scheme
A robust scheme usually includes:
- HTTPS
timestampnonce- signature over canonicalized request data
- short server acceptance window
- replay cache
- idempotency keys for state-changing endpoints
Important caveats
- Bearer tokens alone are replayable if stolen.
- If your timestamp window is too large, replay is still possible.
- If nonce storage is missing or inconsistent across servers, duplicates may slip through.
- Canonicalization matters: sign exactly the same normalized request on both sides.
Practical recommendation
If you’re designing an API from scratch:
- Require TLS.
- Use a signed request format with:
- client ID
- timestamp
- nonce
- body hash
- Reject requests older than a short window.
- Track and reject nonce reuse.
- Add idempotency keys for write operations.
If you want, I can show:
- a concrete HMAC signing example,
- an OAuth/DPoP-based approach,
- or a sample server-side replay protection implementation.