Topics covering webhook creation & management, event handling, Pub/Sub, and Eventbridge, in Shopify apps.
Hi
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 me.
Regards,
Solved! Go to the solution
This is an accepted solution.
I figured out a valid solution
I replaced string to stream for base64 and create webhook from apis not from shop's admin page.
And everything work as expected
Hi MehmetHollyPalm,
Some techniques you could try are:
Try the above and let us know if you're still seeing issues.
Liam | Developer Advocate @ Shopify
- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution
- To learn more visit Shopify.dev or the Shopify Web Design and Development Blog
Hi Liam,
I've tried eveything what u suggest. But result is same
Do u have any change to share some working code example for this situation? Or try my code?
Regards
And I saw an interesting section in my shop settings.
It says that
Your webhooks will be signed with 40376XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (I replaced real chars with X)
But in documentation Shopify says your hmac header encrypted with your "api secret key"
I tried bot of them but can't get result.
Regards
This is an accepted solution.
I figured out a valid solution
I replaced string to stream for base64 and create webhook from apis not from shop's admin page.
And everything work as expected