AWS Builder Center
HMAC Webhook Verification: A Valid Signature Can Still Be a Replay

HMAC Webhook Verification: A Valid Signature Can Still Be a Replay

Verify exact request bytes, bind the timestamp, and persist event receipt safely. HMAC authentication and duplicate-effect prevention solve different problems.

Series: Insights In Plain Text (1 article)

  1. 1
    HMAC Webhook Verification: A Valid Signature Can Still Be a Replay This article
A webhook arrives with a valid signature. Your handler updates the order. The same request arrives again, with the same valid signature. Your handler updates the order again.
HMAC hasn't failed. We asked it to recognize an authentic envelope, then treated every copy as a new instruction. I'd design webhook acceptance around three separate questions: who could have authenticated these bytes, are they recent enough, and have we already accepted this event?
The example here is a deliberately small custom protocol. Use a provider's supported verification library for that provider's webhooks. Header formats and signing inputs are part of its contract, not interchangeable conventions.

Authenticate the bytes you actually received

HMAC combines a secret key with a message to produce an authentication code. Python supplies the construction through its  standard  hmac  module ; there is no reason to implement its inner and outer hashing manually in a webhook handler.
Our sender signs the ASCII timestamp, a period, and the raw request body. The receiver verifies precisely that sequence. Parsing JSON and serializing it again can change whitespace or key order while preserving the same JSON meaning. HMAC authenticates bytes, so that transformation matters.  Stripe's signature troubleshooting guide  describes this exact raw-body integration boundary.
import hmac
import re
import time

def verify_webhook(raw_body, timestamp, signature, secret, now=None):
# Custom protocol: one decimal timestamp and one SHA-256 hex digest.
if not isinstance(raw_body, bytes):
raise ValueError('raw bytes required')
if not re.fullmatch(r'[0-9]{1,12}', timestamp):
raise ValueError('invalid timestamp')
if not re.fullmatch(r'[0-9a-f]{64}', signature):
raise ValueError('invalid signature encoding')
current = int(time.time()) if now is None else now
if abs(current - int(timestamp)) > 300:
raise ValueError('timestamp outside acceptance window')
message = timestamp.encode('ascii') + b'.' + raw_body
expected = hmac.digest(secret, message, 'sha256').hex()
if not hmac.compare_digest(expected, signature):
raise ValueError('signature mismatch')
The timestamp is inside the authenticated message. Moving it into an unsigned header would let an attacker attach a fresh timestamp to an old body and signature. The five-minute interval is an illustrative policy, and the clocks need an operational skew budget. Rate limiting and body-size limits still belong at the HTTP boundary.
Use a high-entropy signing secret from a secret manager, scoped to the integration or endpoint. Passwords and an improvised password-to-key transformation are poor substitutes. If multiple trusted senders share one secret, they can impersonate each other to that receiver.

Freshness still permits duplicates

An attacker can replay a captured request within the acceptance window. Legitimate senders also retry when they don't receive a successful response. Refusing all repetition as malicious would lose useful delivery recovery.
After signature verification, parse the event and extract its provider-assigned identifier. Scope that identifier by integration or account when its uniqueness is not global. Persist an inbox receipt with a uniqueness constraint:
CREATE TABLE webhook_inbox (
integration_id TEXT NOT NULL,
event_id TEXT NOT NULL,
payload BLOB NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
PRIMARY KEY (integration_id, event_id)
);
In a transaction, insert the authenticated event. A uniqueness conflict means the event is already recorded. Return success for a known accepted duplicate according to the provider's contract. If durable receipt fails, return an error so delivery can retry. Acknowledging first and saving later leaves a crash window where an event disappears permanently.
Recording receipt isn't the same as completing the business action. A worker can claim pending rows, perform the work, and persist completion. For a local database update, receipt and mutation may fit in one transaction. For an external side effect, use a stable business idempotency key or an outbox and reconciliation protocol. Marking an event  done  before the effect risks losing it; marking it afterward creates a retry window.

Rotation is an overlap protocol

I'd rotate by publishing a new signing secret and retaining the previous verification secret for a bounded overlap. The verifier should accept only the configured active set, then remove the old key after the agreed delivery and retry horizon. Follow the provider's actual rotation behavior rather than assuming our custom protocol applies.
Do not log signing secrets, full authorization headers, or payloads that may contain private data. Useful logs include integration identifier, event identifier after verification, rejection category, receipt state, and processing result.

Prove the failure paths

The verifier was exercised locally with valid bytes, a one-byte body change, a changed timestamp, an expired request, and malformed signatures. The inbox uniqueness rule was exercised with a duplicate event in SQLite. These checks establish behavior of the example, not end-to-end delivery guarantees for a deployed integration.
Before shipping, also interrupt the process after receipt commit, after the external effect, and before completion commit. Confirm that a retry either completes pending work or reconciles the existing effect. Test reordered events if the business state can move backward when an old update arrives.

Conclusion

I'd keep signature verification, freshness, durable receipt, and business idempotency as separate boundaries with separate tests. HMAC answers an important authenticity question. Reliable webhook processing depends on what the receiver remembers after answering it.
Adapted and substantially updated from  my original article . Technical references reviewed November 8, 2026. Prepared with AI assistance; examples and validation limits are identified in the text.

Series: Insights In Plain Text (1 article)

  1. 1
    HMAC Webhook Verification: A Valid Signature Can Still Be a Replay This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article