正在验证Webhook的请求



我有一个Rails应用程序,它被设置为从WooCommerce接收webhook。具体来说,我正在寻找订单创建的时间。我已经测试并验证了当我有protect_from_forgery(创建除外)时它是否有效。现在我正试图通过验证webhook来保护我的应用程序。WooCommerce的文档指出,请求标头中传递了以下秘密:

secret:一个可选的密钥,用于生成请求主体的HMAC-SHA256散列,以便接收器可以验证web挂钩的真实性

WooCommerce github文档

目前,我不确定该如何验证请求,然后采取行动。如果请求未经授权,请用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网络挂钩,我的问题似乎是适当地获取请求的头文件,以将其与我计算的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

最新更新