Created
November 8, 2023 15:26
-
-
Save martijnlentink/2843bec0b47a81f1fa26fddacd4d5576 to your computer and use it in GitHub Desktop.
Validate Hubspot V3 signature in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private async Task<bool> ValidateSignature(HttpRequestData req, string privateAppValidationSecret) | |
{ | |
var signatureHeader = req.Headers.GetValues("X-HubSpot-Signature-v3").FirstOrDefault(); | |
var timestampHeader = req.Headers.GetValues("X-HubSpot-Request-Timestamp").FirstOrDefault(); | |
if (string.IsNullOrWhiteSpace(signatureHeader) || string.IsNullOrWhiteSpace(timestampHeader)) | |
{ | |
return false; | |
} | |
var timestamp = Convert.ToInt64(timestampHeader); | |
if (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - timestamp > TimeSpan.FromMinutes(5).TotalMilliseconds) | |
{ | |
return false; // Timestamp is too old | |
} | |
var requestUri = System.Net.WebUtility.UrlDecode(req.Url.ToString()); | |
var requestBody = await req.ReadAsStringAsync(); | |
var utf8String = $"{req.Method}{requestUri}{requestBody}{timestampHeader}"; | |
using var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(privateAppValidationSecret ?? throw new ArgumentNullException())); | |
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(utf8String)); | |
var computedSignature = Convert.ToBase64String(hash); | |
return computedSignature == signatureHeader; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment