有人能告诉我如何从WooCommerce网络钩子中重新创建哈希以与请求中的“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
}
}
我也有同样的问题,我是这么做的:
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();
}
更新:要使其工作,您需要转到启动。cs文件并查找“服务.配置”部分。添加选项。AllowSynchronousIO=真;
应该是这样的:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});