如何在Flask/Python中验证Ruby文档的POST请求签名
我正在尝试验证一个POST请求的签名,但到目前为止,我生成的签名哈希值和我通过Flask API生成的测试哈希值不匹配。
文档中列出了以下Ruby代码来验证签名:
payload_body = request.body.read
signature = "sha1=" + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), SECRET_TOKEN, payload_body)
这是我在Flask/Python 3.6中写的代码:
import hashlib, hmac
data=request.get_data()
key=SECRET_TOKEN.encode("utf-8"))
signature = "sha1=" + hmac.new(key, data, hashlib.sha1).hexdigest()
使用以下数据:
SECRET_TOKEN=""
request_data={"type": "verification_approved","data":{"level":"v1","user_id":"d6d782ef-568b-4355-8eb4-2d32ac97b44c"}}
他们得到:
Ruby哈希值: "sha1=2e7c4e307e25dd0ce4baad4d90dc7d4b63bdbab6" # 如文档所示
我得到:
Python哈希值: "sha1=b9361bca2a38228c741ef60296b468693752b76d" # 这是我的实现
任何帮助或指点都将非常感谢!
官方文档在这里: https://docs.developer.fractal.id/user-integration/webhooks/securing-webhooks 和 https://docs.developer.fractal.id/user-integration/webhooks/delivery
相关问题:
- 暂无相关问题
1 个回答
2
根据提供的文档,这就是我实现HMAC SHA1签名验证的方法(这和GitHub处理webhook的方式很相似,这个实现也在那儿有效,不过我更新了头部信息,以符合你的期望):
import hmac
from hashlib import sha1
from flask import request, abort
@app.route("/webhook", methods=["POST"])
def webhook(request):
if "X-Fractal-Signature" not in request.headers:
abort(403)
signature = request.headers.get("X-Fractal-Signature", "").split("=")[1]
# Generate our own signature based on the request payload
secret = os.environ.get('FRACTAL_SECRET', '').encode("utf-8")
mac = hmac.new(secret, msg=request.data, digestmod=sha1)
# Ensure the two signatures match
if not str(mac.hexdigest()) == str(signature):
abort(403)
文档中提到会返回400错误,我个人觉得应该用403错误更合适。