PYTHON
Secure Webhook Handling with Signature Verification
Learn to process incoming webhook payloads in Python, including critical signature verification to ensure the request's authenticity and prevent tampering from malicious sources.
import hmac
import hashlib
import json
from flask import Flask, request, abort # Example using Flask
app = Flask(__name__)
WEBHOOK_SECRET = 'your_super_secret_webhook_key' # Keep this secret and consistent with the sender
@app.route('/webhook', methods=['POST'])
def webhook_receiver():
if request.method == 'POST':
payload = request.data # Raw payload bytes
signature_header = request.headers.get('X-Hub-Signature-256') # Or similar header, e.g., 'Stripe-Signature'
if not signature_header:
abort(400, description="Signature header missing")
# Example: 'sha256=...' format for signature
try:
# Extract the hash part, e.g., from 'sha256=abcdef123...'
algorithm, signature = signature_header.split('=', 1)
except ValueError:
abort(400, description="Invalid signature header format")
if algorithm != 'sha256': # Or other expected algorithm
abort(400, description="Unsupported signature algorithm")
# Generate expected signature
expected_signature = hmac.new(
WEBHOOK_SECRET.encode('utf-8'),
msg=payload,
digestmod=hashlib.sha256
).hexdigest()
# Compare signatures
if not hmac.compare_digest(expected_signature, signature):
abort(403, description="Invalid signature")
# If signature is valid, process the payload
event_data = json.loads(payload.decode('utf-8'))
print(f"Received valid webhook event: {event_data.get('type', 'unknown')}")
# Add your custom logic here based on event_data
# For example, update database, send notification, etc.
return {"status": "success"}, 200
else:
abort(405) # Method Not Allowed
# To run this Flask app:
# FLASK_APP=your_script_name.py flask run
# Remember to expose your local server to the internet using ngrok for testing webhooks.
How it works: This Python snippet, demonstrated with Flask, shows how to set up an endpoint to receive and securely process webhook payloads. The core security measure is signature verification: it uses the `hmac` and `hashlib` modules to generate an expected signature from the incoming payload and a shared secret, then compares it with the signature provided in the request headers. This ensures that the webhook request truly originated from the expected sender and hasn't been tampered with.