How to verify a webhook call?
Intro
In this article, we will show you how to verify webhook calls in your application. This verification ensures that the webhook call actually comes from the expected source (smino api) by using a SHA512 hash generated with a secret key, a timestamp and an event ID.
Prerequisites
A webhook has been set up and a secret has been defined. The webhook call contains a header (x-hook-signature) that contains the hash sent by the server.
Functionality
Verification of a webhook call takes place in three steps:
Extracting the required information: The server sends a hash value in the header of the webhook call, which we intercept with the name x-hook-signature.
Creating the expected hash: We generate a hash from the secret, timestamp and event ID that the webhook contains.
Compare the hashes: The received hash is compared with the hash we generated. If the hashes match, the webhook can be considered verified.
Example in C#
Here is an example code in C# that shows how the verification is performed:
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
var response = new HttpResponseMessage();
const string signatureHeader = “x-hook-signature”;
response.Headers.Add(signatureHeader, “<serverHash>”);
const string secret = “<your secret>”;
var payload = new { ExportId = Guid.NewGuid(), TimeStamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) };
var expectedHash = CreateHash($“{payload.ExportId}.{payload.TimeStamp}.{secret}”);
var responseHash = response.Headers.GetValues(signatureHeader).Single();
VerifyHash(responseHash, expectedHash);
static string CreateHash(string signature)
{
var sha512 = SHA512.Create();
var bytes = Encoding.UTF8.GetBytes(signature);
var hash = sha512.ComputeHash(bytes);
return string.Concat(hash.Select(hashByte => hashByte.ToString(“x2”)));
}
static bool VerifyHash(string responseHash, string expectedHash)
{
return responseHash == expectedHash;
}
Important notes: The timestamp should always be used in UTC time to ensure that it is consistent. Make sure that your secret is stored securely and is not publicly accessible. The x-hook-signature header is crucial as it enables verification. With this approach, you can ensure that webhook calls in your application are authentic and only come from authorized sources.
Updated on: 07/10/2024
Thank you!