Implement HMAC in Azure Function HTTP Trigger

Viewed 61

I was asked to implement HMAC in Azure Function that receives web-hooks requests but I don't find documentations that give me an idea of how to do that. Any suggestion would be great help.

1 Answers

This is not something an azure function can do natively. You'll need to write some custom code to do the following:

  1. Retrieve the HMAC signature sent from the webhook sender. This will likely be sent as a header on the HttpRequestData object you receive (assuming this is azure functions v4).

  2. Compute a hash of the body of the request, using the key that is shared between you and the webhook sender. You can use the System.Security.Cryptography.HMACSHA256 class to do this.:

public string ComputeHMAC(string data, string key)
{
    var dataBytes = Encoding.ASCII.GetBytes(data);
    var keyBytes = Encoding.ASCII.GetBytes(key);

    var hmacHash = HMACSHA256.HashData(keyBytes, dataBytes);

    var hashSB = new StringBuilder();
    for (int i = 0; i < hmacHash.Length; i++)
    {
        hashSB.Append(hmacHash[i].ToString("x2"));
    }

    return hashSB.ToString();
}
  1. Compare your computed hash with the hash received from the webhook sender. If the hashes do not match, you need to reject the webhook request.

You could take this a step further and write an HMAC middleware if you need to do this in different azure functions.

Related