Outbound license event webhooks from Keyright
Stop polling the licensing API to find out what changed. Here is how Keyright pushes signed lifecycle events — activated, revoked, renewed, expiring — to your own endpoint, and how to verify the signature, survive at-least-once delivery, and reject replays on the receiving side.
Most teams learn what their licensing system did by asking it. A nightly job pulls the list of active licenses, diffs it against yesterday’s, and fires the emails and CRM updates that should have gone out hours ago. It works until it matters: a customer refunds at 9am, your “active customers” dashboard still counts them at 5pm, and a renewal reminder lands in the inbox of someone who churned last week. Polling is always stale by design, and the finer you slice the interval the more you hammer an API to mostly learn that nothing changed.
The fix is to invert the flow. Instead of your systems asking the issuing service what changed, the issuing service tells you the moment it changes. That is what Keyright’s outbound event webhooks do: a signed HTTP POST to an endpoint you own, every time a license crosses a lifecycle boundary. This post is about consuming them correctly — the signature, the delivery guarantees, and the replay window — because a webhook endpoint is a public door into your back office, and the three details that make it safe are easy to get wrong.
What an event looks like
Each event is a small JSON document with a stable envelope. The type tells you what happened; the data carries the license it happened to. The envelope fields — id, type, created — are the same across every event, so a single handler can route on type and trust the rest of the shape.
{
"id": "evt_01JD9Q4ZB2K7M3X8V0",
"type": "license.revoked",
"created": "2026-11-13T14:02:11Z",
"data": {
"licenseId": "lic_7c1f9a",
"product": "acme-suite",
"tier": "Pro",
"customerRef": "cust_4821",
"reason": "refund",
"revokedAtUtc": "2026-11-13T14:02:10Z"
}
}
The lifecycle events you will actually wire up are a short list:
license.activated— a key bound to a new device or seat. Trigger provisioning, welcome email, seat-count sync.license.validated.new_node— an existing license checked in from a device it had never used before. Useful for abuse monitoring.license.renewed— a paid renewal extended the expiry. Update the “paid through” date in your CRM.license.expiring— the issuing service’s scheduler fired because a license is inside its renewal window (say, 14 days out). Drive the dunning sequence.license.revoked— a key was revoked (refund, chargeback, manual action). Flip feature flags, notify support.
The delivery path
An event is produced the instant the issuing service commits the state change, handed to a delivery worker, and POSTed to your subscribed URL. If your endpoint is slow, down, or returns a non-2xx, the worker retries with backoff. That retry behavior is the single most important thing to design for, and the diagram makes the consequence concrete: the same event can arrive more than once.
This is at-least-once delivery, and it is the correct guarantee: the alternative — at-most-once — would silently drop events whenever your endpoint hiccupped, which is worse than seeing one twice. Your job on the receiving side is to make a duplicate harmless.
Detail 1 — verify the signature over the raw body
Your webhook URL is reachable by anyone who learns it. If your handler acts on whatever it receives, someone can POST a license.renewed for an account that never paid. The defense is an HMAC the issuing service computes over the payload with a secret only the two of you hold, sent in X-Keyright-Signature alongside an X-Keyright-Timestamp. The signed string is the timestamp and the raw body joined by a dot — binding the signature to a moment in time as well as to the bytes.
The trap that burns everyone: verify over the exact raw bytes you received, before you deserialize anything. Model binding re-serializes JSON with different whitespace and key order, and the recomputed HMAC will never match. Read the body as a string once, verify, then parse.
app.MapPost("/webhooks/keyright", async (HttpRequest req) =>
{
using var reader = new StreamReader(req.Body);
string rawBody = await reader.ReadToEndAsync(); // the exact bytes, untouched
string signature = req.Headers["X-Keyright-Signature"];
string timestamp = req.Headers["X-Keyright-Timestamp"];
if (!WebhookVerifier.IsValid(rawBody, timestamp, signature, Secret))
return Results.Unauthorized();
var evt = JsonSerializer.Deserialize<WebhookEvent>(rawBody)!; // safe to parse now
await _dispatcher.HandleAsync(evt);
return Results.Ok();
});
The verifier recomputes the HMAC and compares in constant time — a plain == on the hex strings leaks, through timing, how many leading bytes matched, which is enough to forge a signature byte by byte. CryptographicOperations.FixedTimeEquals closes that door.
public static class WebhookVerifier
{
public static bool IsValid(string body, string timestamp, string header, byte[] secret)
{
// Reject anything older than five minutes: shrinks the replay window.
if (!long.TryParse(timestamp, out var unix)) return false;
var age = DateTimeOffset.UtcNow - DateTimeOffset.FromUnixTimeSeconds(unix);
if (age > TimeSpan.FromMinutes(5) || age < TimeSpan.FromMinutes(-5)) return false;
var signed = Encoding.UTF8.GetBytes($"{timestamp}.{body}");
var expected = HMACSHA256.HashData(secret, signed);
Span<byte> provided = stackalloc byte[32];
if (!Convert.TryFromHexString(header, provided, out int n) || n != 32) return false;
return CryptographicOperations.FixedTimeEquals(expected, provided);
}
}
Detail 2 — make the consumer idempotent
Because delivery is at-least-once, your handler must produce the same result whether it sees an event one time or five. Key your processing on the envelope’s id, which is stable across retries of the same event, and record it the first time you act. A second arrival finds the record and returns early.
public async Task HandleAsync(WebhookEvent evt)
{
// INSERT ... ON CONFLICT DO NOTHING on the event id; 0 rows means we have seen it.
if (!await _events.TryClaimAsync(evt.Id))
return; // duplicate — already processed, ack it
switch (evt.Type)
{
case "license.revoked": await _crm.MarkChurnedAsync(evt.Data.CustomerRef); break;
case "license.renewed": await _crm.ExtendPaidThroughAsync(evt.Data); break;
case "license.expiring": await _dunning.StartAsync(evt.Data); break;
// ignore event types you do not handle — do not 4xx them, just ack
}
}
Note the last comment. Return 2xx for events you do not care about. A 4xx tells the issuing service delivery failed, so it will keep retrying an event you were never going to use, and your retry queue backs up behind it.
Respond fast, work later
The delivery worker has a timeout. If your handler does real work — sending email, calling a CRM — inside the request, a slow dependency turns into a webhook timeout and an unnecessary retry. For anything beyond a quick write, claim the event id, enqueue the work to your own background processor, and return 200 immediately. You have acknowledged receipt; the processing is now your problem, not the issuing service’s.
Configuring a subscription
Subscriptions are managed through the Keyright CLI against your self-hosted instance. Create one with the destination URL and the event types you want; the command returns the signing secret once, which you store wherever your app reads its secrets.
keyright webhooks create \
--url https://api.acme.example/webhooks/keyright \
--events license.activated,license.renewed,license.revoked,license.expiring \
--product acme-suite
# -> endpoint whk_4f91, signing secret whsec_... (shown once)
Subscribe only to the events you handle. A narrower subscription is less traffic, a smaller attack surface, and a clearer contract for the next engineer reading your handler.
Webhooks notify; the SDK enforces
One boundary is worth stating plainly, because conflating it causes real outages. Webhooks are for your back-office systems — CRM, email, dashboards, provisioning. They are not how the licensed application decides whether to run. That decision stays inside the app, which initializes the Keyright SDK with its product and public key and calls Validate against the signed license it holds, gating features fail-closed.
var keyright = new KeyrightClient(product: "acme-suite", publicKey: EmbeddedKey);
var info = await keyright.ValidateAsync();
if (!info.IsValid || !info.Entitlements.Has("export"))
throw new FeatureLockedException("export"); // fail closed, locally, every time
Keep the two concerns separate and both get simpler. A webhook that is delayed by a retry storm still cannot let an unlicensed app run, because the app never trusted the webhook in the first place. And a license check that fails offline still works, because it does not depend on your CRM having heard the news. The webhook is how your business learns about a license change in real time; the signed license and the SDK gate are how your software enforces it.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.