In .net 8 app I wanna validate webhook’s payload for security.
Here is the my code and always return false because of my calculation and hmac header doesn’t match.
private bool ValidateHash(ActionExecutingContext actionContext)
{
actionContext.HttpContext.Request.Body.Position = 0;
using var stream = new MemoryStream();
actionContext.HttpContext.Request.Body.CopyToAsync(stream).Wait();
var requestBody = Encoding.UTF8.GetString(stream.ToArray());
var svc = actionContext.HttpContext.RequestServices;
var shopifySettings = svc.GetService<IOptions<ShopifySettings>>()?.Value;
var keyBytes = Encoding.UTF8.GetBytes(shopifySettings.ApiSecretKey);
var dataBytes = Encoding.UTF8.GetBytes(requestBody);
var hmac = new HMACSHA256(keyBytes);
var hmacBytes = hmac.ComputeHash(dataBytes);
var hmacHeader = actionContext.HttpContext.Request.Headers["x-shopify-hmac-sha256"];
var createSignature = Convert.ToBase64String(hmacBytes);
return hmacHeader == createSignature;
}
Also I buffered my http request for reliable streaming
app.Use(next => context =>
{
context.Request.EnableBuffering();
return next(context);
});
Please help.
Regards,