Receiving webhooks: signature verification, replay protection and idempotent processing
Whether it is a payment provider, a shipping company or a source code platform, once you integrate with an external system you will sooner or later write a webhook endpoint. The first version is usually ten lines: read the JSON, look at the event type, update the database, return 200. It works without issues in the development environment.
The problem is that this endpoint is open to the internet and the party calling it is not under your control. Someone of unknown identity can send a fake "payment received" event, the real sender can deliver the same event three times, and events can arrive in reverse order. In this post I harden a webhook receiver step by step on ASP.NET Core: signature verification, replay protection, fast responses and idempotent processing.
A webhook endpoint is not an ordinary endpoint
In your own API you know the caller: there is a session cookie or an access token, and your authorization layer is in play. A webhook has none of that. The endpoint is public and its address will show up somewhere sooner or later; keeping the address secret is not a security measure.
The second difference is the delivery guarantee. Senders almost always implement "at least once" delivery: when they get no response or see an error code, they send the event again. So the same event arriving more than once is not an exception, it is part of the contract.
Third, you do not control the timing. The sender expects a response within a short time and may deliver events in bursts and without any ordering guarantee. These three properties shape the rest of the design: verify identity, respond quickly, and tolerate duplicates and reordering.
Verifying the signature over the raw body
The common method is an HMAC signature. You and the sender share a secret; the sender signs the request body with that secret and sends the signature in a header. You perform the same computation and compare the results. Someone who does not know the secret cannot produce a valid signature.
The most frequent mistake is parsing the body as JSON first and then signing a re-serialized version. Whitespace, field order or number formatting changes and the signature no longer matches. The signature must be computed over the bytes that came off the network, which is why you read the body yourself instead of relying on model binding.
public sealed class WebhookSignatureVerifier(
IOptions<WebhookOptions> options, TimeProvider timeProvider)
{
private const long ToleranceSeconds = 300;
public bool IsValid(byte[] body, string timestamp, string signature)
{
if (!long.TryParse(timestamp, out var sentAt))
return false;
var now = timeProvider.GetUtcNow().ToUnixTimeSeconds();
if (sentAt < now - ToleranceSeconds || sentAt > now + ToleranceSeconds)
return false;
byte[] provided;
try { provided = Convert.FromHexString(signature); }
catch (FormatException) { return false; }
byte[] signed = [.. Encoding.UTF8.GetBytes(timestamp + "."), .. body];
foreach (var secret in options.Value.Secrets)
{
var expected = HMACSHA256.HashData(
Encoding.UTF8.GetBytes(secret), signed);
if (CryptographicOperations.FixedTimeEquals(expected, provided))
return true;
}
return false;
}
}
The comparison uses CryptographicOperations.FixedTimeEquals rather than == or SequenceEqual. An ordinary comparison stops at the first differing byte; that small difference in response time can give an attacker a way to guess the signature byte by byte. A constant-time comparison does not leak that information.
Header names, whether the signature is hex or Base64, and the exact format of the signed text vary by sender. The example here assumes a "timestamp, dot, body" format; you need to implement exactly the format described in the documentation of the system you integrate with.
Replay protection with a timestamp
A signature proves that the request came from the real sender, but it says nothing about when. Someone who captures a valid request can resend it unchanged days later and the signature will still match. This is called a replay attack.
The solution is to include a timestamp in the signature. In the code above the signed data contains the timestamp along with the body, so if the attacker changes the timestamp the signature breaks. The receiver in turn rejects the request when the timestamp falls outside a certain tolerance. Five minutes is a common value: wide enough to absorb clock drift and network delay, narrow enough to limit the lifetime of a captured request.
The signature cannot stop replays made within the tolerance window. Those are caught by the event ID check described in the following sections. The two measures complement each other: the timestamp filters out old requests, the ID check filters out fresh duplicates.
Store first, process later
The sender expects a response quickly. If you take the request and right then send emails, call other services and generate reports, the processing time can exceed the sender's timeout. The sender counts that as a failure and sends the event again, while you start doing the same work one more time.
A more robust approach is for the endpoint to do a single job: verify the signature, persist the event, return 200. The actual processing happens in the background.
app.MapPost("/webhooks/payments", async (
HttpRequest request,
WebhookSignatureVerifier verifier,
AppDbContext db,
TimeProvider timeProvider,
CancellationToken ct) =>
{
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer, ct);
var body = buffer.ToArray();
var timestamp = request.Headers["X-Webhook-Timestamp"].ToString();
var signature = request.Headers["X-Webhook-Signature"].ToString();
if (!verifier.IsValid(body, timestamp, signature))
return Results.Unauthorized();
var envelope = JsonSerializer.Deserialize<WebhookEnvelope>(
body, JsonSerializerOptions.Web);
if (envelope is null || string.IsNullOrEmpty(envelope.Id))
return Results.BadRequest();
db.InboxMessages.Add(new InboxMessage
{
Id = envelope.Id,
Type = envelope.Type,
Payload = Encoding.UTF8.GetString(body),
ReceivedAt = timeProvider.GetUtcNow()
});
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateException ex) when (ex.IsUniqueViolation())
{
// The event was already received; no need to store it again.
}
return Results.Ok();
});
IsUniqueViolation is a small helper method that checks the error code of your database provider; it does not come built in. The example is also kept simple: in production you need to put an upper limit on the body size and catch JsonException for malformed JSON to return 400.
Pay attention to the order: JSON parsing comes after the signature has been verified. There is no reason to interpret the contents of an unauthenticated request. Once the event is stored, a background service reads the unprocessed rows and does the actual work; if processing fails, the event stays in the table and can be retried.
Making duplicate events harmless
In the inbox table the event ID is the primary key. When the sender delivers the same event again, the insert hits the uniqueness constraint, the endpoint still returns 200 and no second row is created. Returning 200 here matters: if you return an error, the sender keeps sending an event you already have.
This makes receiving idempotent; processing has to be idempotent too. The background service can crash after processing the event but before marking the row as processed, and the event gets processed a second time. The way around this is to write the business change and the "processed" marker in the same database transaction. Either both become durable or neither does.
Side effects that leave the transaction, such as sending an email or calling another API, fall outside this guarantee. For those you need to pass an idempotency key derived from the event ID to the system you call, or split the side effect into a separate step that keeps its own record.
Out-of-order events and current state
Senders usually give no ordering guarantee. A "subscription updated" event can arrive before the "subscription created" event; because of a retry, an old event can show up after a newer one. Blindly applying events in arrival order can roll a record back to a stale state.
There are two practical methods. The first is to store the version number or creation time carried by the event along with the record, and ignore an event when it is older than what you have. The second is to treat the event as a notification rather than a data source: when an event arrives, you read the current state of the resource from the sender's API and write your own record accordingly. That means an extra call, but it removes the ordering problem entirely and reduces your dependence on the fields in the event body.
If an event arrives for a record that does not exist yet, leaving it in the table and retrying later is usually the right behavior instead of treating it as an error and dropping it; the missing event is most likely on its way.
Secret rotation, response codes and monitoring
The shared secret should be changed over time, and that change has to happen without downtime. This is why the verifier accepts a list instead of a single secret: during rotation the old and the new secret are both valid, and once the sender has switched to the new one, the old one is removed from the list. The secret itself belongs in a secret store, not in a configuration file, and must never be written to logs.
Response codes tell the sender what to do, so they should be chosen deliberately. 2xx if the event was stored or is already stored; 401 if the signature is invalid; 5xx if the database write failed. In the last case you want the sender to retry, because you do not have the event yet. You should also return 2xx for an event type you do not recognize; returning an error causes an event you will never use to be resent indefinitely.
On the monitoring side three signals are useful: the number of rejected signatures, the number of events waiting to be processed, and the age of the oldest waiting event. The first points to a misconfigured secret or an attack attempt, the other two to a stuck processor. Because the verifier takes a TimeProvider, the tolerance window is easy to test by advancing the clock; a valid signature, a broken signature, an old timestamp and a duplicate event are the minimum set of tests to write.
Conclusion
What makes a webhook receiver reliable is applying together a handful of decisions that are not hard individually. You verify the signature over the raw bytes with a constant-time comparison; you reject old requests using the timestamp; you store the event first, respond quickly and do the work in the background; you neutralize duplicates with the event ID, and reordering with version information or by reading the current state. With these pieces in place, the sender's retries stop being a problem and instead become a safety net that makes up for the events your system missed.