Webhook Payload Validation Guide
Validating the integrity and authenticity of a webhook payload is crucial for security and reliability. This guide provides steps to validate a webhook payload using a signature
header, where the signature is a SHA256 hash of the payload.
Steps for Validation
Extract the Signature from the Header: The webhook request will contain a header named
signature
in the formatsha256=<value>
. You'll need to parse this header to extract the<value>
part.Compute the HMAC SHA256 Hash of the Payload: Using the same secret key that was used to generate the signature, compute the HMAC SHA256 hash of the payload received in the webhook.
Compare the Computed Hash with the Received Signature: The validation is successful if the computed hash matches the signature extracted from the header.
C# Example
Below is an example in C# demonstrating how to validate a webhook payload:
using System;
using System.Security.Cryptography;
using System.Text;
public class WebhookValidator
{
// The secret key used to generate the signature
private static readonly string secretKey = "your_secret_key_here";
public static bool ValidatePayload(string payload, string receivedSignature)
{
using (var hasher = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)))
{
// Compute the HMAC SHA256 hash of the payload
var hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(payload));
var computedSignature = BitConverter.ToString(hash).Replace("-", "");
// Extract the actual signature value from the received 'sha256=<value>' format
var expectedSignature = receivedSignature.StartsWith("sha256=") ? receivedSignature.Substring(7) : receivedSignature;
// Compare the computed hash with the received signature
return computedSignature.Equals(expectedSignature, StringComparison.Ordinal);
}
}
}
Replace your_secret_key_here with your actual secret key used for generating the signature. Ensure that the payload variable contains the raw payload as a string, and the signature variable contains the complete content of the signature header.
Security Note
Always ensure that the secret key is stored securely and not hard-coded in your source code. Consider using environment variables or secure vaults for storing such sensitive information.