Round #344
08 May 2026, 16:53· csharp· qwen2.5-coder-7b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 5 / 4 / 1
- Journey weight
- 612
- Lightshift ΔL
- +0.17
Prompt
Implement a webhook delivery endpoint with HMAC signature verification
Zero-point index (what the engine surfaced)
ZPI-ZPI-0003 | 2026-05-08T16:53:32Z
Implement a webhook delivery endpoint with HMAC signature verification
ZERO POINT — 5 entries (structural invariants)
● hsl(27.69, 100%, 50%) async [feature]
● hsl(145.64, 100%, 27%) Task of T [feature]
● hsl(7.18, 100%, 38%) class [feature]
● hsl(0.00, 100%, 38%) public [feature]
● hsl(84.10, 100%, 38%) namespace [feature]
UNOBSERVED — 4 entries (implied truths)
○ hsl(9.23, 100%, 50%) interface [feature]
○ hsl(77.54, 100%, 36%) Routing middleware [function]
○ hsl(83.08, 100%, 42%) ILogger of T injection [function]
○ hsl(31.38, 100%, 42%) Scoped registration [function]
OBSERVED — 1 entries (explicit in request)
◉ hsl(98.46, 100%, 28%) with [feature]
COMPLEXITY │ 10 entries │ spread: 89° │ band: LOW
Baseline response (no ZPI)
To implement a webhook delivery endpoint with HMAC signature verification in C#, you can follow these steps:
1. **Create an ASP.NET Core Web API project**: If you don't already have one, create a new ASP.NET Core Web API project.
2. **Add necessary NuGet packages**: Ensure you have the necessary packages installed. You might need `Microsoft.AspNetCore.Mvc` and `System.Security.Cryptography`.
3. **Implement the webhook endpoint**: Create a controller to handle incoming webhook requests.
4. **Verify HMAC signature**: Implement logic to verify the HMAC signature of the incoming request.
Here's a complete example:
### Step 1: Create an ASP.NET Core Web API project
You can create a new project using Visual Studio or the .NET CLI:
```bash
dotnet new webapi -n WebhookReceiver
cd WebhookReceiver
```
### Step 2: Add necessary NuGet packages
Ensure you have the necessary packages installed. You might need `Microsoft.AspNetCore.Mvc` and `System.Security.Cryptography`.
```bash
dotnet add package Microsoft.AspNetCore.Mvc
dotnet add package System.Security.Cryptography
```
### Step 3: Implement the webhook endpoint
Create a new controller to handle incoming webhook requests.
```csharp
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class WebhookController : ControllerBase
{
private readonly string _secretKey = "your-secret-key"; // Replace with your actual secret key
[HttpPost]
public async Task<IActionResult> ReceiveWebhook()
{
if (!Request.Headers.TryGetValue("X-Hmac-Signature", out var hmacSignature))
{
return BadRequest("Missing X-Hmac-Signature header");
}
if (!Request.Body.CanSeek)
{
Request.EnableBuffering();
}
using (var reader = new System.IO.StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
{
var requestBody = await reader.ReadToEndAsync();
// Verify the HMAC signature
if (!VerifyHmacSignature(requestBody, hmacSignature))
{
return Unauthorized("Invalid HMAC signature");
}
// Process the webhook payload
// For example, log it or perform some action
Console.WriteLine($"Received webhook: {requestBody}");
return Ok("Webhook received and verified successfully");
}
}
private bool VerifyHmacSignature(string requestBody, string hmacSignature)
{
using (var hmac = System.Security.Cryptography.HMACSHA256.Create())
{
hmac.Key = Encoding.UTF8.GetBytes(_secretKey);
var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(requestBody));
var computedBase64 = Convert.ToBase64String(computedHash);
return computedBase64.Equals(hmacSignature, StringComparison.OrdinalIgnoreCase);
}
}
}
```
### Step 4: Configure the application
Ensure your `Startup.cs` or `Program.cs` is configured to use the controller.
For .NET Core 3.1 and later:
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
```
### Step 5: Run the application
Run your application using the following command:
```bash
dotnet run
```
Your webhook endpoint should now be running and capable of receiving and verifying HMAC signatures.
### Notes:
- Replace `"your-secret-key"` with your actual secret key.
- Ensure that the `X-Hmac-Signature` header is included in the incoming requests from the webhook sender.
- This example uses SHA256 for the HMAC algorithm. You can choose other algorithms if needed.
This setup provides a basic implementation of a webhook delivery endpoint with HMAC signature verification. Depending on your requirements, you might need to add more security measures or handle different types of webhooks.
Enhanced response (with ZPI)
To implement a webhook delivery endpoint with HMAC signature verification, we'll create an ASP.NET Core controller action. This action will handle incoming webhooks, verify the HMAC signature using the provided key, and process the payload if the signature is valid.
Here's the complete implementation:
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class WebhookController : ControllerBase
{
private readonly ILogger<WebhookController> _logger;
private readonly string _hmacKey;
public WebhookController(ILogger<WebhookController> logger, IOptions<HmacSettings> hmacSettings)
{
_logger = logger;
_hmacKey = hmacSettings.Value.Key;
}
[HttpPost]
public async Task<IActionResult> ReceiveWebhook([FromBody] string payload)
{
try
{
if (!Request.Headers.TryGetValue("X-HMAC-Signature", out var signatureHeader))
{
return Unauthorized("Missing HMAC Signature");
}
var providedSignature = signatureHeader.ToString();
var calculatedSignature = CalculateHmacSignature(payload, _hmacKey);
if (providedSignature != calculatedSignature)
{
return Unauthorized("Invalid HMAC Signature");
}
// Process the valid webhook payload
await ProcessWebhookPayload(payload);
return Ok("Webhook processed successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing webhook");
return StatusCode(500, "Internal Server Error");
}
}
private string CalculateHmacSignature(string payload, string key)
{
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
return Convert.ToBase64String(hashBytes);
}
private async Task ProcessWebhookPayload(string payload)
{
// Implement your webhook processing logic here
_logger.LogInformation("Processing webhook payload: {Payload}", payload);
await Task.CompletedTask;
}
}
public class HmacSettings
{
public string Key { get; set; }
}
```
### Explanation:
1. **Controller and Action**:
- The `WebhookController` is decorated with `[ApiController]` and `[Route("api/[controller]")]` to define the base route for webhook requests.
- The `ReceiveWebhook` action handles POST requests and expects a JSON payload.
2. **Dependency Injection**:
- The constructor injects an `ILogger<WebhookController>` for logging and an `IOptions<HmacSettings>` to retrieve the HMAC key from configuration.
3. **HMAC Signature Verification**:
- The action checks if the `X-HMAC-Signature` header is present in the request.
- It calculates the expected HMAC signature using the provided payload and the stored HMAC key.
- If the calculated signature matches the provided signature, the payload is considered valid.
4. **Payload Processing**:
- If the signature is valid, the `ProcessWebhookPayload` method is called to handle the webhook data.
- This method can be customized to include your specific processing logic.
5. **Error Handling**:
- The action includes basic error handling to log exceptions and return appropriate HTTP status codes.
6. **Configuration**:
- The HMAC key should be stored in the application's configuration (e.g., `appsettings.json`):
```json
{
"HmacSettings": {
"Key": "your-hmac-key"
}
}
```
This implementation provides a robust and secure way to handle webhook deliveries with HMAC signature verification.
Grader chain
Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.
V1claude-sonnet-4-6
SameV4qwen2.5-coder-7b-instruct
BetterComments
Our grader said what it said. What do you say? Comment as a guest below.
No comments yet. Be the first to say what you make of this round.