Created
March 2, 2023 20:21
-
-
Save tipenehughes/4ba4babd0bad3440253ec9d3dde6d4d0 to your computer and use it in GitHub Desktop.
Verifying webhook authenticity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request | |
import hashlib | |
import hmac | |
import base64 | |
# Signing secret from webhook itself | |
SIGNING_SECRET = "{your_signing_secret}" | |
# Always sha256 | |
SIGNING_SECRET_ALGORITHM = "sha256" | |
PORT = 8000 | |
app = Flask(__name__) | |
def isValidSignature(signature, body, timestamp): | |
hmac_obj = hmac.new(bytes(SIGNING_SECRET, 'utf-8'), digestmod=hashlib.sha256) | |
hmac_obj.update(bytes(timestamp + body, 'utf-8')) | |
sig = hmac_obj.digest() | |
return hmac.compare_digest(signature.encode(), base64.b64encode(sig)) | |
def storeRawBody(): | |
raw_body = request.data.decode('utf-8') | |
request.rawBody = raw_body | |
# Use middleware to store raw request body depending on request format | |
app.before_request(storeRawBody) | |
@app.route('/hook', methods=['POST']) | |
def webhook(): | |
# Fields from the webhook request, this will change every time | |
signature = request.headers.get('x-zendesk-webhook-signature') | |
timestamp = request.headers.get('x-zendesk-webhook-signature-timestamp') | |
body = request.rawBody | |
print("HMAC signature is valid" if isValidSignature(signature, body, timestamp) else "HMAC signature is invalid") | |
return "Success", 200 | |
if __name__ == '__main__': | |
app.run(port=PORT, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment