【问题标题】:WooCommerce webhook c# - compare hashWooCommerce webhook c# - 比较哈希
【发布时间】:2020-05-18 08:20:17
【问题描述】:

谁能告诉我如何从 WooCommerce webhook 重新创建散列,以与请求中的“X-WC-Webhook-Signature”标头散列进行比较?

文档指定哈希是从“有效负载”生成的,但我无法生成相同的哈希。

我的 API 是 .NET Core 3.1

我尝试的第一件事:

var secret = "XXX";
var requestHash = Request.Headers["X-WC-Webhook-Signature"];
var generatedHash = "";
Stream byteContent = Request.Body;
byte[] keyByte = encoding.GetBytes(secret);
using(var hmacsha256 = new HMACSHA256(keyByte))
{
     byte[] hashmessage = hmacsha256.ComputeHash(byteContent);
     generatedHash = Convert.ToBase64String(hashmessage);
 }
 if(requestHash == generatedHash)
 {
     // Succes
 }

第二:

using(StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
    String json = await reader.ReadToEndAsync();
    var generatedHash = "";
    byte[] messageBytes = encoding.GetBytes(json);
    keyByte = encoding.GetBytes(secret);
    using(var hmacsha256 = new HMACSHA256(keyByte))
    {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        generatedHash = Convert.ToBase64String(hashmessage);
    }

    if(requestHash == generatedHash)
    {
        // Succes
    }
}

【问题讨论】:

    标签: c# .net-core woocommerce hook-woocommerce


    【解决方案1】:

    我遇到了同样的问题,这就是我所做的:

    using System.Security.Cryptography;
    
    if (Request.Headers.TryGetValue("X-WC-Webhook-Signature", out var headerValues))
    {
        XWCWebhookSignature = headerValues.FirstOrDefault();
    }
    
    var encoding = new UTF8Encoding();
    var key = "yourKeyValue";
    var keyBytes = encoding.GetBytes(key);
    var hash = new HMACSHA256(keyBytes);
    var computedHash = hash.ComputeHash(Request.Body);
    var computedHashString = System.Convert.ToBase64String(computedHash);
    
    if (XWCWebhookSignature != computedHashString)
    {
        return Unauthorized();
    }
    

    更新:为此,您需要转到 Startup.cs 文件并找到“services.Configure”部分。 添加 options.AllowSynchronousIO = true;

    应该是这样的:

    services.Configure<IISServerOptions>(options =>
      {
         options.AllowSynchronousIO = true;
      });
    

    【讨论】:

    • 显然我不能使用 'hash.ComputeHash(Request.Body)'.. 我收到错误消息:“不允许同步操作。请调用 ReadAsync 或将 AllowSynchronousIO 设置为 true。”
    猜你喜欢
    • 2011-03-27
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多