【问题标题】:Verifying request of Webhook验证 Webhook 的请求
【发布时间】:2015-04-07 01:32:43
【问题描述】:

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

secret:一个可选的密钥,用于生成请求正文的 HMAC-SHA256 哈希,以便接收者可以验证网络挂钩的真实性

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

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

【问题讨论】:

  • 我无法提供解决方案,但您所做的似乎完全正常。大多数时候我遇到这个问题,它就像一个流浪的换行符一样愚蠢,但我看到你最后打电话给strip

标签: ruby-on-rails wordpress webhooks


【解决方案1】:

好的,我发现了我遇到的问题。如果其他人正在尝试使用 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

【讨论】:

  • “Digest::Digest 已弃用;使用 Digest”(来自日志)
  • 您不应该使用直接相等运算符 (==) 来比较 webhook。使用Rack::Utils.secure_compare
猜你喜欢
  • 2021-12-21
  • 2015-12-31
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2022-01-14
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多