2012-11-06 38 views
2

我已經設置了一個端點來接收來自Shopify的webhook請求。如何創建一個匹配的HMAC值來驗證.NET中的Shopify WebHook?

來自Shopify的請求包括從共享密鑰和請求主體創建的HMAC標頭。

我需要計算我的服務器上的HMAC並將其與請求頭中的值匹配以確保請求是可信的。

我似乎無法在.NET中創建適當的機制來創建匹配的HMAC值。

我在這一點上的算法如下:

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); 
    } 

的Shopify文檔驗證他們的網絡掛接,可以發現HERE但只有PHP和Ruby的樣本都包括在內。

任何人都可以看到我可能做錯了什麼?我應該只是將整個JSON請求體作爲字符串傳遞給此方法嗎?

回答

3

正如你在你的問題中提到的,你應該在你的方法中散列整個json請求體。

我的.NET不是太好,但這裏的紅寶石例子的一部分,顯示你該怎麼做:

post '/' do 

    . . . 

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

    . . . 

end 

你可以看到,我們只是抓住了請求的主體(作爲一個字符串),並逐字將其扔入驗證方法。試試看,希望你會有更多的運氣。

+0

謝謝,我認爲這是正確的做法。我仍然需要有人確認我上面的哈希機制是正確的......即符合Shopify在它們的最後完成的方式。 – stephen776

4
private static bool Validate(string sharedSecretKey) 
    { 
     var data = GetStreamAsText(HttpContext.Current.Request.InputStream, HttpContext.Current.Request.ContentEncoding); 
     var keyBytes = Encoding.UTF8.GetBytes(sharedSecretKey); 
     var dataBytes = Encoding.UTF8.GetBytes(data); 

     //use the SHA256Managed Class to compute the hash 
     var hmac = new HMACSHA256(keyBytes); 
     var 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. 
     var hmacHeader = HttpContext.Current.Request.Headers["x-shopify-hmac-sha256"]; 
     var createSignature = Convert.ToBase64String(hmacBytes); 
     return hmacHeader == createSignature; 
    } 

    private static string GetStreamAsText(Stream stream, Encoding encoding) 
    { 
     var bytesToGet = stream.Length; 
     var input = new byte[bytesToGet]; 
     stream.Read(input, 0, (int)bytesToGet); 
     stream.Seek(0, SeekOrigin.Begin); // reset stream so that normal ASP.NET processing can read data 
     var text = encoding.GetString(input); 
     return text; 
    } 
+0

這不是他們在他們的網站上定義的。他們提到的數據是商店和時間戳。試過了,不能讓它工作 – MBen

相關問題