In this lesson, you will learn how to verify incoming webhook signatures to ensure that the data your application processes genuinely originates from a trusted API provider.
When a service (like Stripe or GitHub) sends an asynchronous webhook to your server, your endpoint is essentially "public." Anyone who guesses your URL could send a fake request to trigger actions in your system. To prevent this, API providers include a digital signature in the request headers, usually generated by hashing the request payload with a shared secret key.
The Verification Workflow
- Receive the Raw Payload: You must access the raw, unmodified request body as bytes. If you parse it into JSON before verifying, whitespace differences or encoding issues will cause the signature check to fail.
- Compute the Signature: Using the shared secret provided by the API partner, you hash the raw body (typically using HMAC-SHA256) in your Python code.
- Compare: Compare your computed hash with the one provided in the request headers (often
X-Hub-SignatureorX-Signature). If they match exactly, the request is authentic.
Here is a simplified example using Python’s hmac and hashlib libraries:
import hmac
import hashlib
def verify_webhook(request_body, received_signature, secret_key):
# Create the HMAC object with your secret and SHA256
expected_hmac = hmac.new(
secret_key.encode(),
request_body,
hashlib.sha256
).hexdigest()
# Use hmac.compare_digest to prevent timing attacks
return hmac.compare_digest(expected_hmac, received_signature)
Why timing matters
Always use hmac.compare_digest() rather than the standard == operator for string comparison. Standard comparisons return False as soon as the first mismatched character is found, which allows attackers to measure the time it takes to respond and eventually guess your signature character by character. compare_digest takes a constant amount of time, neutralizing this vulnerability.
Once verified, you can safely proceed to parse the JSON and execute your business logic, such as updating a database or triggering a background task.
Key Takeaway: Never trust webhook data blindly; always verify the signature using the raw request body and a constant-time comparison to ensure the payload is authentic and untampered.