如何创建匹配的HMAC值以验证.NET中的Shopify WebHook? [英] How can I create a matching HMAC value to verify a Shopify WebHook in .NET?

查看:297
本文介绍了如何创建匹配的HMAC值以验证.NET中的Shopify WebHook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个端点来接收来自Shopify的Webhook请求.

I have set up an endpoint to receive webhook requests from Shopify.

来自Shopify的请求包括一个HMAC头,该头是根据共享密钥和请求的主体创建的.

The requests from Shopify include an HMAC header that is created from a shared secret key and the body of the request.

我需要在服务器上计算HMAC并将其与请求标头中的值匹配,以确保请求是真实的.

I need to calculate the HMAC on my server and match it to the value in the request header to ensure that the request is authentic.

我似乎无法在.NET中创建适当的机制来创建匹配的HMAC值.

I can't seem to create the appropriate mechanism in .NET to create a matching HMAC value.

这时我的算法如下:

public static string CreateHash(string data)
    {
        string sharedSecretKey = "MY_KEY";

        byte[] keyBytes = Encoding.UTF8.GetBytes(sharedSecretKey);
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);

        //use the SHA256Managed Class to compute the hash
        System.Security.Cryptography.HMACSHA256 hmac = new HMACSHA256(keyBytes);
        byte[] hmacBytes = hmac.ComputeHash(dataBytes);

        //retun as base64 string. Compared with the signature passed in the header of the post request from Shopify. If they match, the call is verified.
        return System.Convert.ToBase64String(hmacBytes);
    }

可以在 HERE 中找到用于验证其Webhooks的Shopify文档,但仅包含PHP和Ruby示例.

The Shopify docs for verifying their webhooks can be found HERE but only PHP and Ruby samples are included.

谁能看到我可能做错了什么?我是否应该将整个JSON请求主体作为字符串传递给此方法?

Can anyone see what I might be doing wrong? Should I be just passing the entire JSON request body as a string into this method?

推荐答案

正如您在问题中提到的那样,您应该在方法中对整个json请求主体进行哈希处理.

As you allude to in your question, you should be hashing the entire json request body in your method.

我的.NET不太好,但这是ruby示例的一部分,向您展示了如何做:

My .NET isn't too good, but Here's the part of the ruby example that shows you what to do:

post '/' do

  . . .

  data = request.body.read
  verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"])

  . . .

end

您可以看到我们只是在抓取请求的主体(作为字符串),并将其逐字地扔入verify方法.试试看,希望您会遇到更多的运气.

You can see that we're just grabbing the body of the request (as a string) and throwing it into the verify method verbatim. Give it a try and hopefully you'll have more luck.

这篇关于如何创建匹配的HMAC值以验证.NET中的Shopify WebHook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆