DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Verifying inbound billing webhooks in .NET

A license server is only as trustworthy as the events it reacts to. When a customer is refunded, your payment provider sends a webhook; your back-end revokes the license; the next verification fails closed. The whole chain hinges on one assumption — that the POST really came from the provider. Strip that away and anyone who learns the endpoint URL can revoke a competitor's license, or grant themselves a perpetual one, with a single curl.

Providers solve this by signing each webhook with a shared secret. The signature is only as good as your verification of it, and that verification is where most integrations quietly go wrong.

The real question

What exactly are you verifying, and against what? A naive handler reaches for the parsed body and a string compare:

// WRONG on three counts
app.MapPost("/billing/webhook", (BillingEvent evt, HttpRequest req) =>
{
    var sig = req.Headers["X-Signature"].ToString();
    var expected = Convert.ToHexString(Hmac(JsonSerializer.SerializeToUtf8Bytes(evt)));
    if (sig == expected) Apply(evt);   // (1) re-serialized body (2) == compare (3) no freshness
    return Results.Ok();
});
Enter fullscreen mode Exit fullscreen mode

Every line here is a hole. The body was re-serialized, so the bytes no longer match what was signed. The comparison is ==, which leaks timing. And nothing stops an attacker from capturing one real webhook and replaying it a thousand times. Let's fix all three.

The signed content

A typical provider sends a header that carries both a timestamp and one or more signatures:

X-Keyright-Signature: t=1763305200,v1=4f2d...e9 (64 hex chars)
Enter fullscreen mode Exit fullscreen mode

The signature v1 is HMAC-SHA256(secret, signedContent), and the signed content is not the body alone — it is the timestamp, a separator, and the raw body bytes concatenated:

signedContent = "1763305200" + "." + <raw request body bytes>
Enter fullscreen mode Exit fullscreen mode

Binding the timestamp into the HMAC is what makes replay defense possible: you can't keep the signature and lie about when it was issued, because the time is part of what was signed.










Four independent gates. Authenticity (HMAC), integrity (same raw bytes), freshness (timestamp window) and uniqueness (replay cache) must all pass before a billing event touches license state.

The verifier

Here is a correct verifier. It parses the header, enforces the timestamp window, recomputes the HMAC over the exact signed content, and compares in constant time.

using System.Globalization;
using System.Security.Cryptography;
using System.Text;

public sealed class WebhookVerifier(string signingSecret)
{
    private readonly byte[] _secret = Encoding.UTF8.GetBytes(signingSecret);
    private readonly TimeSpan _tolerance = TimeSpan.FromMinutes(5);

    public bool TryVerify(byte[] rawBody, string signatureHeader, DateTimeOffset now)
    {
        if (!TryParseHeader(signatureHeader, out long ts, out byte[] provided))
            return false;

        // Freshness: a valid signature is not a fresh one.
        var skew = now - DateTimeOffset.FromUnixTimeSeconds(ts);
        if (skew.Duration() > _tolerance)
            return false;

        // Signed content is exactly: "<t>." followed by the raw body bytes.
        byte[] prefix = Encoding.ASCII.GetBytes(
            ts.ToString(CultureInfo.InvariantCulture) + ".");
        byte[] signed = new byte[prefix.Length + rawBody.Length];
        Buffer.BlockCopy(prefix, 0, signed, 0, prefix.Length);
        Buffer.BlockCopy(rawBody, 0, signed, prefix.Length, rawBody.Length);

        byte[] expected = HMACSHA256.HashData(_secret, signed);

        // Constant-time: never ==.
        return CryptographicOperations.FixedTimeEquals(expected, provided);
    }

    private static bool TryParseHeader(string header, out long ts, out byte[] v1)
    {
        ts = 0; v1 = [];
        if (string.IsNullOrEmpty(header)) return false;
        foreach (var part in header.Split(','))
        {
            var kv = part.Split('=', 2);
            if (kv.Length != 2) continue;
            switch (kv[0].Trim())
            {
                case "t":
                    if (!long.TryParse(kv[1], NumberStyles.None,
                        CultureInfo.InvariantCulture, out ts)) return false;
                    break;
                case "v1":
                    try { v1 = Convert.FromHexString(kv[1].Trim()); }
                    catch (FormatException) { return false; }
                    break;
            }
        }
        return ts != 0 && v1.Length == 32; // SHA-256 is 32 bytes
    }
}
Enter fullscreen mode Exit fullscreen mode

Three details carry the security. HMACSHA256.HashData keys the hash with the shared secret, so only someone holding it can produce a matching digest. FixedTimeEquals compares all 32 bytes regardless of where they first differ, so no timing oracle leaks. And the timestamp is inside signed, so it cannot be altered without invalidating v1.

Capturing the exact bytes

The verifier is useless if you hand it the wrong bytes. In ASP.NET Core, the moment you bind a model the framework reads and discards the request stream, and even if you re-serialize the parsed object you get different bytes than the provider signed. Read the raw body first:

app.MapPost("/billing/webhook",
    async (HttpRequest req, WebhookVerifier verifier, IReplayCache seen,
           ILicenseStore store) =>
{
    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    byte[] raw = ms.ToArray();               // exactly what was signed

    var sig = req.Headers["X-Keyright-Signature"].ToString();
    if (!verifier.TryVerify(raw, sig, DateTimeOffset.UtcNow))
        return Results.Unauthorized();        // 401: one message for every failure

    var evt = JsonSerializer.Deserialize<BillingEvent>(raw)!;

    // Replay defense: ack duplicates without re-applying them.
    if (!await seen.TryAddAsync(evt.Id, TimeSpan.FromHours(24)))
        return Results.Ok();

    await Reconcile(evt, store);
    return Results.Ok();
});
Enter fullscreen mode Exit fullscreen mode

Only after verification is it safe to deserialize. The replay cache stores each event id with a TTL that comfortably exceeds the provider's retry horizon; a second delivery of the same id is acknowledged with 200 but does nothing. Returning 200 rather than an error is deliberate — the event was handled, so you don't want the provider to keep retrying.

Reconciling into license state

With a trustworthy event in hand, the mapping to Keyright is small. A refund or a dispute revokes; a successful renewal extends. Keep the switch narrow and fail closed on anything unexpected:

static async Task Reconcile(BillingEvent evt, ILicenseStore store) =>
    _ = evt.Type switch
    {
        "charge.refunded"        => await store.RevokeByOrderAsync(evt.OrderId, evt.Type),
        "charge.dispute.created" => await store.RevokeByOrderAsync(evt.OrderId, evt.Type),
        "subscription.renewed"   => await store.ExtendByOrderAsync(evt.OrderId, evt.PeriodEnd),
        _                        => false // unknown types are logged, not trusted
    };
Enter fullscreen mode Exit fullscreen mode

Once revoked, the next SDK verification fails closed and the customer's entitlements — a vendor-chosen set such as max_projects, feature.export, or max_major_version — stop granting. The revocation propagates through Keyright's normal client blocklist and grace-window machinery; the webhook is only the trigger, not a new enforcement path.

Caveats and when it breaks

Secret rotation needs an overlap. When you roll the signing secret, accept either secret for a window: try the new one, then the old, before rejecting. A verifier that knows only one secret turns every rotation into an outage.

Don't do slow work inline. Payment providers expect a fast 2xx and will retry if you block on a long database transaction. Verify, enqueue, ack — then reconcile out of band, keyed by the event id so retries stay idempotent.

One error for every failure. Return the same 401 whether the timestamp is stale, the id is malformed, or the HMAC is wrong. A verbose error ("bad timestamp" vs "bad signature") hands an attacker a probing oracle.

The tolerance is a trade-off. Five minutes forgives ordinary clock skew between your server and the provider. Too wide and a captured webhook stays replayable longer than your cache remembers it; too narrow and legitimate deliveries fail when a clock drifts. Sync your server clock with NTP and keep the window tight.

Takeaway

An inbound webhook is an untrusted POST until four independent checks pass: the HMAC proves it came from your provider, the raw bytes prove it wasn't altered, the timestamp proves it's fresh, and the replay cache proves it's new. Skip any one and the quietest part of your licensing system — the part that revokes on a refund — becomes the easiest to forge. Verify over the bytes that were actually signed, compare in constant time, and only then let a billing event touch a license.

Top comments (0)