验证 Webhook 请求

Verifying request of Webhook

我有一个 Rails 应用程序设置为从 WooCommerce 接收 webhook。具体来说,我正在寻找何时创建订单。我已经测试并验证了当我有 protect_from_forgery 除了创建时它可以工作。现在我正尝试通过验证 webhook 来保护我的应用程序。 WooCommerce 的文档说明在请求 header:

中传递了以下秘密

secret: an optional secret key that is used to generate a HMAC-SHA256 hash of the request body so the receiver can verify authenticity of the web hook

WooCommerce github doc

目前我不确定我应该如何验证请求,然后采取行动。如果请求未被授权,则使用 401 拒绝它。这就是我正在尝试的:

class HooksController < ApplicationController

    protect_from_forgery
    before_action :restrict_access

    def order_created_callback
    ...
    end

    private

    SHARED_SECRET = 'my_secret_key'

    def verify_webhook(data, hmac_header)
        digest  = OpenSSL::Digest::Digest.new('sha256')
        calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, SHARED_SECRET, data)).strip
        calculated_hmac == hmac_header
    end

    def restrict_access
        data = request.body.read
        verified = verify_webhook(data, env["X-WC-Webhook-Signature"])
        head :unauthorized unless verified

    end
end

但是到目前为止我一直没有成功。任何投入将不胜感激。谢谢

好的,我发现了我遇到的问题。如果其他人正在尝试使用 WooCommerce web hook,我的问题似乎是适当地获取请求的头文件以将其与我计算的 HMAC 相匹配。

SHARED_SECRET = "my_secret"

def verify_webhook(data, hmac_header)
    hash  = OpenSSL::Digest::Digest.new('sha256')
    calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(hash, SHARED_SECRET, data)).strip
    Rack::Utils.secure_compare(calculated_hmac, hmac_header)
end

def restrict_access
    data = request.body.read
    head = request.headers["X-WC-Webhook-Signature"]
    verified = verify_webhook(data, head)
    if verified
        return
    else
        render nothing: true, status: :unauthorized
    end
end