---
title: "C# webhook signature verifier"
description: "Run the complete C# raw-byte notification verifier with authenticated event and environment checks."
slug: "/docs/v1/guides/verify-webhook-signatures/csharp"
section: "Webhook verification examples"
order: 218
audience: "all"
level: "advanced"
last_updated: "2026-10-18"
version: "v1"
related: ["/docs/v1/guides/verify-webhook-signatures", "/docs/v1/guides/test-webhooks-locally"]
draft: false
---
Authenticate [KDPika Licensing](/docs/v1/start/glossary#kdpika-licensing) notification bytes with the complete C# verifier.

## What you will learn

- Install and execute this exact sample.
- Verify raw bytes, event metadata and the pinned environment.
- Identify the boundary between authentication and durable business processing.

## Prerequisites

- .NET SDK supporting the net7.0 target; no NuGet dependencies. Verify any supported-runtime target upgrade in your deployment.
- The [notification source archive](/docs/downloads/webhook-receivers.zip), extracted locally.
- The [signature contract](/docs/v1/guides/verify-webhook-signatures) and a private [Sandbox](/docs/v1/start/glossary#sandbox) test secret.

## Prepare a request

1. Work inside the extracted [webhooks](/docs/v1/start/glossary#webhook) directory, which contains contract.json.
2. Set KDP_WEBHOOK_SECRET through your private process environment.
3. Set KDP_WEBHOOK_ENVIRONMENT to sandbox.
4. Use Python 3.11+ to create a fresh private synthetic request.

```bash
python3 make-test.py events/test-ping.json private/request-1
```

Expected output: Created private test request files. Use a new directory for each generated request; existing files are not overwritten. The helper signs a captured synthetic body, not a real payment or [license](/docs/v1/start/glossary#license) authorization. Keep contract.json in place: it supplies the shared event list, 300-second receiver freshness policy and 1 MiB receiver body cap.

## Build and run

```bash
dotnet build csharp/WebhookVerifier.csproj -c Release
dotnet csharp/bin/Release/net7.0/WebhookVerifier.dll private/request-1/body.json private/request-1/headers.json
```

Expected result: exit 0 with verified=true, event_id=evt_ffa11b785e0ede73d9e69801, event=test.ping and environment=sandbox. Property order is not significant. This source was executed in the recorded macOS contract suite; native Windows and Linux execution are not claimed.

## Complete source

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType><TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
    <RestoreIgnoreFailedSources>true</RestoreIgnoreFailedSources>
  </PropertyGroup>
</Project>
```

```csharp
// Notification authenticity, not license validity. .NET 7+, standard library only.
// Build: dotnet build -c Release; run from the parent folder containing contract.json.
// Set KDP_WEBHOOK_SECRET/KDP_WEBHOOK_ENVIRONMENT; dotnet csharp/bin/Release/net7.0/WebhookVerifier.dll body.json headers.json
// Expected: verified=true JSON; invalid input prints verified=false and exits 1.
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

static class WebhookVerifier
{
    static byte[] Bounded(string path,int limit)
    {
        using var file=File.OpenRead(path);using var output=new MemoryStream();var buffer=new byte[8192];int read;
        while((read=file.Read(buffer,0,Math.Min(buffer.Length,limit+1-(int)output.Length)))>0){output.Write(buffer,0,read);if(output.Length>limit)throw new InvalidDataException();}
        return output.ToArray();
    }
    static bool Includes(JsonElement array,string value)=>array.EnumerateArray().Any(item=>item.GetString()==value);
    static string Text(JsonElement obj,string key)=>obj.GetProperty(key).GetString()??throw new InvalidDataException();
    public static JsonElement Verify(byte[] body,JsonElement headers,string secret,string environment,long now,JsonElement contract)
    {
        if(secret.Length==0||!Includes(contract.GetProperty("environments"),environment)||body.Length>contract.GetProperty("body_limit").GetInt32())throw new InvalidDataException();
        var match=Regex.Match(Text(headers,"x-lmp-signature"),@"\At=([1-9][0-9]{0,10}),v1=([0-9a-f]{64})\z",RegexOptions.CultureInvariant);
        if(!match.Success||Math.Abs(now-long.Parse(match.Groups[1].Value))>contract.GetProperty("tolerance_seconds").GetInt32())throw new InvalidDataException();
        var prefix=Encoding.ASCII.GetBytes(match.Groups[1].Value+".");var message=new byte[prefix.Length+body.Length];prefix.CopyTo(message,0);body.CopyTo(message,prefix.Length);
        using var hmac=new HMACSHA256(Encoding.UTF8.GetBytes(secret));
        if(!CryptographicOperations.FixedTimeEquals(hmac.ComputeHash(message),Convert.FromHexString(match.Groups[2].Value)))throw new InvalidDataException();
        _=new UTF8Encoding(false,true).GetString(body);
        using var document=JsonDocument.Parse(body);var item=document.RootElement;
        if(item.ValueKind!=JsonValueKind.Object||!Regex.IsMatch(Text(item,"id"),@"\Aevt_[A-Za-z0-9_-]{1,100}\z")||!Includes(contract.GetProperty("events"),Text(item,"event"))||Text(item,"environment")!=environment||Text(item,"id")!=Text(headers,"x-lmp-event-id")||Text(item,"event")!=Text(headers,"x-lmp-event"))throw new InvalidDataException();
        if(Text(item,"created_at").Length==0||item.GetProperty("data").ValueKind!=JsonValueKind.Object)throw new InvalidDataException();
        return item.Clone();
    }
    static int Main(string[] args)
    {
        try{
            if(args.Length!=2)throw new InvalidDataException();
            using var contract=JsonDocument.Parse(Bounded("contract.json",32768));using var headers=JsonDocument.Parse(Bounded(args[1],32768));
            var item=Verify(Bounded(args[0],1048576),headers.RootElement,Environment.GetEnvironmentVariable("KDP_WEBHOOK_SECRET")??"",(Environment.GetEnvironmentVariable("KDP_WEBHOOK_ENVIRONMENT")??"").ToLowerInvariant(),DateTimeOffset.UtcNow.ToUnixTimeSeconds(),contract.RootElement);
            Console.WriteLine(JsonSerializer.Serialize(new{verified=true,event_id=Text(item,"id"),@event=Text(item,"event"),environment=Text(item,"environment")}));return 0;
        }catch(Exception){Console.WriteLine("{\"verified\":false}");return 1;}
    }
}
```

## Connect to an HTTP adapter

1. Read a bounded raw HTTP body before JSON middleware changes it.
2. Reject duplicate signature, event-ID and event-name header fields.
3. Normalize header names to lowercase without changing their values.
4. Pass the exact raw body, headers, configured endpoint secret and expected environment to the verifier.
5. Atomically persist the verified event ID and work item before sending a 2xx response.

Expected result: only authenticated recent notifications reach your inbox. The CLI tool does not start an HTTP listener, save deduplication records, call licensing APIs, send email or unlock an application. Use the [local inbox example](/docs/v1/guides/test-webhooks-locally) to test the durable acknowledgement boundary.

## Expected result

All captured event types pass when signed with the right current secret and pinned environment. Changed raw bytes, a wrong secret, stale/future attempt timestamp, malformed envelope or wrong environment print exactly {"verified":false} and exit 1. The shared suite exercises positive events, negative input and size boundaries against the exact file above.

## Common mistakes

- Reading contract.json from a different working directory or copying only one source without its companion files.
- Re-encoding JSON before HMAC verification.
- Reusing an expired test signature instead of generating a current one.
- Assuming successful authentication deduplicates an additive renewal.

## Security notes

Never print the secret or full signature in logs. Use the endpoint's plaintext HMAC secret, not a [developer API key](/docs/v1/start/glossary#developer-api-key) or an Ed25519 public key. A verified notification is not an authoritative license-validity response. Timestamp filtering does not stop duplicate [delivery](/docs/v1/start/glossary#delivery) inside its window; use a durable authenticated event-ID ledger and an independent business-operation key.

## Troubleshooting

| Symptom | Cause | Fix |
| --- | --- | --- |
| verified=false for an unchanged fixture | Timestamp expired, wrong secret or wrong environment | Regenerate the private request using the intended Sandbox configuration |
| Companion file cannot be found | Working directory or extraction incomplete | Restore the complete source archive and work inside webhooks |
| The same ID verifies again | Verifier only authenticates bytes | Commit a unique inbox record before applying an effect |

## Next steps

Run the [local HTTP, replay and storage-failure tests](/docs/v1/guides/test-webhooks-locally).

## Related

- [All verifier languages](/docs/v1/guides/verify-webhook-signatures)
- [Delivery and retries](/docs/v1/guides/webhook-delivery)
- [Webhook event catalog](/docs/v1/guides/webhook-events)
