WooCommerce webhook c# - 比较哈希 [英] WooCommerce webhook c# - compare hash

查看:35
本文介绍了WooCommerce webhook c# - 比较哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我如何从 WooCommerce webhook 重新创建哈希以与请求中的X-WC-Webhook-Signature"标头哈希进行比较?

Can someone tell me how I can recreate the hash from WooCommerce webhook to compare with the "X-WC-Webhook-Signature" header hash from the request?

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

The documentation specifies the hash is generated from the 'payload', but I am unable to generate the same hash.

我的 API 是 .NET Core 3.1

My API is .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
    }
}

推荐答案

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

I had the same problem and here's what I did:

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;

Update: For this to work you will need to go to Startup.cs file and find "services.Configure" section. Add options.AllowSynchronousIO = true;

它应该是这样的:

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

这篇关于WooCommerce webhook c# - 比较哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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