Standard Webhooks
Standard Webhooks is a Python library for securely handling webhooks conforming to the Standard Webhooks specification. It provides functionalities for signature verification, content encryption, and replay protection, ensuring the authenticity and integrity of incoming webhook payloads. The current version is 1.0.1, with active development and maintenance.
Warnings
- gotcha The webhook secret must be provided as a `bytes` object when initializing the `Webhook` class. Providing a `str` will result in a `TypeError` or unexpected behavior during signature verification.
- gotcha It is crucial to handle `WebhookVerificationError` exceptions. If this exception is raised, the incoming webhook is invalid, tampered with, or expired. Ignoring this error can lead to security vulnerabilities.
- gotcha The `webhook.verify()` method expects the raw request body as `bytes`. Do not pass a decoded string or a parsed JSON object, as this will prevent correct signature verification.
Install
-
pip install standardwebhooks
Imports
- Webhook
from standardwebhooks import Webhook
- WebhookVerificationError
from standardwebhooks import WebhookVerificationError
- WebhookSigningError
from standardwebhooks import WebhookSigningError
Quickstart
import os
from standardwebhooks import Webhook, WebhookVerificationError
# In a real application, the secret should be securely loaded from environment variables or a secret store.
# It MUST be bytes.
WEBHOOK_SECRET = os.environ.get('STANDARDWEBHOOKS_SECRET', 'whsec_testsecretforlocaldevelopmentonly').encode('utf-8')
# Example incoming webhook data (replace with actual request data)
headers = {
'Webhook-Id': 'msg_00000000000000000000000000',
'Webhook-Timestamp': '2024-04-10T12:00:00Z',
'Webhook-Signature': 'v1,sig_00000000000000000000000000',
'Content-Type': 'application/json'
}
body = b'{"key": "value"}' # Body must be bytes
# Initialize the Webhook handler with your secret
webhook = Webhook(WEBHOOK_SECRET)
try:
# Verify the incoming webhook
# In a web framework, you would pass request.headers and request.body
verified_data = webhook.verify(headers=headers, body=body)
print("Webhook verified successfully!")
print("Payload:", verified_data)
except WebhookVerificationError as e:
print(f"Webhook verification failed: {e}")
# Important: Log the error but do not expose details to the client.
# Return a 400 or 401 status code.
except Exception as e:
print(f"An unexpected error occurred: {e}")
# To simulate a successful verification, you'd need a valid signature for the given secret, body, id, and timestamp.
# The example above uses placeholder values for demonstration.