我有一个Rails应用程序,它被设置为从WooCommerce接收一个web钩子。具体来说,我正在寻找当一个订单被创建。除了create之外,我已经测试并验证了当我有protect_from_forgery时它是否工作。现在,我正试图通过验证web钩子来保护我的应用程序。WooCommerce的文档声明在请求头中传递了以下秘密:
秘密:一种可选的密钥,用于生成请求主体的HMAC- that 256散列,以便接收方能够验证web钩子的真实性。
目前,我不知道该如何核实请求,然后对其采取行动。如果请求未被授权,则以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
但到目前为止我一直没有成功。如有任何意见,将不胜感激。谢谢。
发布于 2015-04-11 07:52:42
好吧,我想出了我的问题。如果其他人试图使用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
https://stackoverflow.com/questions/29482286
复制相似问题