Webhook signature verification helps you check that messages you get really come from the right sender and not from someone pretending to be them.
0
0
Webhook signature verification in Rest API
Introduction
When you receive data from a service and want to be sure it is safe and not fake.
When you want to protect your app from bad actors sending false information.
When you need to trust that the webhook data has not been changed during transmission.
When you want to follow security best practices for APIs and webhooks.
Syntax
Rest API
1. Receive webhook request with headers and body. 2. Extract the signature from the request headers. 3. Use your secret key to create a hash of the request body. 4. Compare your hash with the signature from the header. 5. If they match, accept the webhook; otherwise, reject it.
The secret key is shared only between you and the webhook sender.
Hashing algorithms like HMAC with SHA256 are commonly used.
Examples
This example shows how to compare the signature header with your computed hash in Python.
Rest API
signature = request.headers['X-Signature'] computed_hash = hmac.new(secret_key, request.body, hashlib.sha256).hexdigest() if hmac.compare_digest(signature, computed_hash): process_webhook() else: reject_request()
This JavaScript example uses Node.js crypto to verify the webhook signature safely.
Rest API
const signature = req.headers['x-signature']; const computedHash = crypto.createHmac('sha256', secretKey) .update(req.body) .digest('hex'); if (crypto.timingSafeEqual(Buffer.from(signature, 'utf8'), Buffer.from(computedHash, 'utf8'))) { processWebhook(); } else { rejectRequest(); }
Sample Program
This program simulates receiving a webhook with a signature and verifies it using HMAC SHA256. It prints a message depending on whether the signature matches.
Rest API
import hmac import hashlib # Simulated webhook request data request_body = b'{"order_id":12345,"status":"paid"}' secret_key = b'mysecretkey' # Simulate signature sent by webhook sender signature = hmac.new(secret_key, request_body, hashlib.sha256).hexdigest() # Function to verify webhook signature def verify_webhook(body, signature, secret): computed_hash = hmac.new(secret, body, hashlib.sha256).hexdigest() return hmac.compare_digest(signature, computed_hash) # Check the webhook if verify_webhook(request_body, signature, secret_key): print("Webhook verified: process the data") else: print("Webhook verification failed: reject the data")
OutputSuccess
Important Notes
Always use a timing-safe comparison function like hmac.compare_digest to avoid timing attacks.
Keep your secret key private and never share it publicly.
Check the webhook documentation for the exact header name and hashing method used.
Summary
Webhook signature verification confirms the webhook is from a trusted source.
It uses a secret key and hashing to compare signatures safely.
Always reject webhooks if the signature does not match.