Webhook HMAC-SHA256 Verifier · .NET / ASP.NET Core

ASP.NET Core 8/9 Raw Body Webhook HMAC Verification (EnableBuffering Guide)

Verify and generate .NET / ASP.NET Core HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·X-Signature-256

X-Signature-256: 1a0cae67dc8a10006fb77dce495b7506351150fb2b785dce562f02d55e0c69a1

// Program.cs — ASP.NET Core 8/9 Raw Body Webhook Verification
using System.Security.Cryptography;
using System.Text;

app.MapPost("/webhooks/generic", async (HttpRequest request, IConfiguration config) =>
{
    request.EnableBuffering();
    request.Body.Position = 0;
    using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true);
    var rawBody = await reader.ReadToEndAsync();
    request.Body.Position = 0;

    var secret = config["Webhooks:Secret"]!;
    var received = request.Headers["X-Signature-256"].ToString();
    var signingPayload = rawBody;

    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
    var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(signingPayload));
    var expected = Convert.ToHexString(hashBytes).ToLowerInvariant();

    var isValid = CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected),
        Encoding.UTF8.GetBytes(received)
    );

    return isValid ? Results.Ok(new { received = true }) : Results.BadRequest("Invalid signature");
});
1. Raw Body HMAC (HEX)Valid

1a0cae67dc8a10006fb77dce495b7506351150fb2b785dce562f02d55e0c69a1

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

a3a657b0543e31a17e5c1ac3df08c3b341cc2a66cc9a513a0f1b587eb2a02abd

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (.NET / ASP.NET Core)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in .NET / ASP.NET Core, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

System.NotSupportedException: Specified method is not supported (Request.Body.Position = 0) — Request.EnableBuffering() was not called before reading raw webhook stream.

Raw Request Stream Handling & Replay Protection in .NET / ASP.NET Core

Verifying webhook HMAC-SHA256 signatures in ASP.NET Core 8 and 9 Web APIs (whether Minimal APIs or MVC Controllers) revolves around one fundamental Kestrel stream rule: HttpRequest.Body is a forward-only, non-seekable network stream by default. If ASP.NET Core model binding ([FromBody] MyEventDto payload) reads the stream first, you cannot rewind it; and serializing the C# DTO back via JsonSerializer.Serialize(payload) destroys the original JSON formatting and invalidates the HMAC.

To inspect untouched raw bytes cleanly in .NET 8 and 9, call request.EnableBuffering() BEFORE reading the stream (either inside a dedicated endpoint filter / middleware or directly at the top of a Minimal API handler without a [FromBody] parameter). Reading the stream with StreamReader(.., leaveOpen: true) and resetting request.Body.Position = 0 lets downstream JSON deserialization or logging read the exact same payload safely.

For cryptographic verification, .NET provides HMACSHA256 and CryptographicOperations.FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) directly in System.Security.Cryptography; zero external NuGet dependencies required. Unlike string == comparison, FixedTimeEquals executes in constant time and safely returns false (without throwing an exception!) if the two byte spans differ in length.

When deploying ASP.NET Core behind Nginx, remember to match Nginx client_max_body_size with Kestrel's MaxRequestBodySize and offload slow downstream database or HTTP calls to a Channel<T> + BackgroundService (or Hangfire/MassTransit) so webhook senders receive HTTP 200 OK in milliseconds.

Use the interactive Web Crypto debugger above to generate Hex or Base64 test signatures across Stripe, GitHub, Shopify, Slack, or Generic HMAC formats and copy the complete C# snippet.

Enterprise ASP.NET Core 8 and 9 webhook receivers benefit from encapsulating EnableBuffering(), UTF-8 raw stream reading, and CryptographicOperations.FixedTimeEquals() inside a reusable IEndpointFilter or middleware scoped strictly to /webhooks/* routes. Combined with .NET's System.Threading.Channels or MassTransit for asynchronous fulfillment and structured Serilog telemetry on verification failures, your Kestrel API handles high-volume webhook bursts reliably behind Nginx.

Step-by-Step .NET / ASP.NET Core Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Build a Reusable ASP.NET Core Endpoint Filter for Raw Body HMAC Checks

    Filters/WebhookHmacEndpointFilter.cs

    Call EnableBuffering(), compute HMACSHA256 over the untouched UTF-8 bytes, verify in constant time via CryptographicOperations.FixedTimeEquals(), and rewind Body.Position to 0.

    Filters/WebhookHmacEndpointFilter.cscsharp
    using System.Security.Cryptography;
    using System.Text;
    
    public sealed class WebhookHmacEndpointFilter(IConfiguration config) : IEndpointFilter
    {
        public async ValueTask<object?> InvokeAsync(
            EndpointFilterInvocationContext context,
            EndpointFilterDelegate next)
        {
            var request = context.HttpContext.Request;
            request.EnableBuffering();
            request.Body.Position = 0;
    
            using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true);
            var rawBody = await reader.ReadToEndAsync();
            request.Body.Position = 0;
    
            var received = request.Headers["X-Signature-256"].ToString();
            var secret = config["Webhooks:Secret"] ?? string.Empty;
            if (string.IsNullOrEmpty(received) || string.IsNullOrEmpty(secret))
                return Results.Unauthorized();
    
            using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(rawBody));
            var expected = Convert.ToHexString(hash).ToLowerInvariant();
    
            var valid = CryptographicOperations.FixedTimeEquals(
                Encoding.UTF8.GetBytes(expected),
                Encoding.UTF8.GetBytes(received)
            );
    
            return valid ? await next(context) : Results.Unauthorized();
        }
    }
  2. 2Attach the Filter to Your Minimal API Webhook Endpoint

    Program.cs

    Because the filter rewinds request.Body.Position = 0 after verifying the raw stream, your endpoint handler can still bind a strongly typed C# record cleanly.

    Program.cscsharp
    app.MapPost("/webhooks/orders", (OrderWebhookEvent payload) =>
    {
        // Signature is already verified over raw bytes!
        return Results.Accepted(value: new { payload.EventId });
    })
    .AddEndpointFilter<WebhookHmacEndpointFilter>();
  3. 3Configure Webhooks__Secret via Environment Variables in Linux/Docker

    .env

    Inject Webhooks:Secret using ASP.NET Core's double-underscore convention so secrets never live in appsettings.json.

    .envdotenv
    Webhooks__Secret="whsec_demo_dotnet_kestrel_secret_2026"
  4. 4Test With curl Using --data-binary and Generated Signature

    terminal

    Send a formatted JSON file with --data-binary so curl preserves exact newlines and indentation.

    terminalbash
    curl -i -X POST http://127.0.0.1:5000/webhooks/orders \
      -H "Content-Type: application/json" \
      -H "X-Signature-256: <paste_hex_from_tool>" \
      --data-binary @order-event.json

Common .NET / ASP.NET Core Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Forgetting leaveOpen: true on StreamReader Closing Request.Body Prematurely

Disposing a default StreamReader closes the underlying Request.Body stream, causing subsequent JSON model binding to throw ObjectDisposedException. Always pass leaveOpen: true and rewind Position = 0.

Pitfall 2

Convert.ToHexString() Returning Uppercase Hex in .NET

In .NET 5–8, Convert.ToHexString() returns UPPERCASE hex ("A1B2.."), whereas Stripe, GitHub, and Slack send lowercase hex ("a1b2.."). Always call .ToLowerInvariant() (or Convert.ToHexStringLower() in .NET 9+).

Pitfall 3

Enabling EnableBuffering() Globally for Massive File Upload Endpoints

Buffering large requests in memory/disk can increase memory pressure under attack. Apply EnableBuffering() selectively only on /webhooks/* endpoints using an Endpoint Filter or scoped middleware.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Does CryptographicOperations.FixedTimeEquals throw an exception if lengths differ?
No. Unlike Node.js crypto.timingSafeEqual (which throws RangeError on mismatched lengths), .NET's CryptographicOperations.FixedTimeEquals safely returns false when the two ReadOnlySpan<byte> lengths differ.
How do I adapt this ASP.NET Core filter for Shopify Base64 HMAC headers?
Replace Convert.ToHexString(hash).ToLowerInvariant() with Convert.ToBase64String(hash) and read the X-Shopify-Hmac-Sha256 header instead.
Why does [FromBody] return an empty body if I read Request.Body inside an MVC Controller?
MVC model binding runs BEFORE your controller action executes, consuming the non-seekable stream first. Either enable buffering in a Middleware/ResourceFilter before model binding, or omit [FromBody] and deserialize rawBody manually with JsonSerializer.Deserialize<T>(rawBody).
Should I run AllowAnonymous on ASP.NET Core webhook endpoints?
Yes, if your API uses a global JWT fallback authorization policy. Mark webhook routes [AllowAnonymous] and rely on your HMAC signature filter to authenticate external webhook providers.
Browse all 10 webhook guides →