Verifying the Webhook Signature
"Signature Auth" Webhook Subscription
SmarterPay Cloud sends a signature with all “Signature Auth” Webhook Subscriptions.
This signature can be used to verify that the contents of the webhook has not been tampered with.
The steps detailed below show one way to verify the Webhook Signature.
Step 1: Extract the Signature from the Webhook
The signature is sent in the “Webhook-Signature” message header of the Webhook.
Step 2: Compute the expected signature
- Generate a byte array of the Webhook Key, for the Subscription.
- Generate a byte array of the unformatted raw webhook body.
- Generate a signature hash, with an instance of HMACSHA256, using the the byte array of the webhook key as the secret key
- Remove any “-” characters from the result.
- Make the result lowercase.
.NET Code Example:
string secret = "ssecretwebhookkey"; string message ="{ \"events\" :[ { \"id\" : \"0\" , \"created_at\" : \"2021-08-25T17:18:03.000Z\", \"resource_type\": \"mandate\", \"event_source\" : \"10044000\", \"customer_account\" : \"\", " + " \"AUDDIS\" : \"0\", \"status\" : \"new_instruction\", \"description\" : \"Test for webhook Mandate Subscription\", \"bacs_reason_code\" : \"200 OK\", \"bacs_description\" : \"Test\", " + " \"bacs_reference\" : \"\", \"bacs_filename\" : \"\" } ] }"; // Get Byte Array From Webhook Key AKA Secret Key byte[] key = Encoding.UTF8.GetBytes(secret); // Get Byte Array from message byte[] bytes = Encoding.UTF8.GetBytes(message); //Generate Instance of 256 using the key array HMACSHA256 hmacsha256 = new HMACSHA256(key); // Compute a hash using the instance of the sha256. byte[] hash = hmacsha256.ComputeHash(bytes); // Get Hash string calculatedSignature = BitConverter.ToString(hash).Replace("-", "").ToLower();
Step 3: Compare the Signatures
Compare the signature passed with the Webhook, from Step 1, with the expected signature, from step 2.