HTTP Signature for Webhooks
When receiving webhooks, it's important to verify that the payload is sent by a trusted source and has not been tampered with. This is commonly achieved by using an HTTP signature, where the sender signs the payload using a secret key and a hashing algorithm (e.g., SHA256). The receiver can then verify the signature using the same secret key.
How HTTP Signature Works
-
Sender Side (Webhook Provider):
- The payload (usually the request body) is hashed using HMAC with SHA256 and a shared
webhook_secret_key
. - The resulting signature is sent in a header (e.g.,
X-Signature
orX-Webhook-Signature
).
- The payload (usually the request body) is hashed using HMAC with SHA256 and a shared
-
Receiver Side (Your Server):
- Upon receiving the webhook, your server computes the HMAC SHA256 hash of the received payload using the same
webhook_secret_key
. - It compares the computed signature with the one provided in the header.
- If they match, the payload is authentic.
- Upon receiving the webhook, your server computes the HMAC SHA256 hash of the received payload using the same
Example: Generating HTTP Signature in Node.js
const crypto = require('crypto');
function generateSignature(payload, webhookSecretKey) {
// payload: string (raw request body)
// webhookSecretKey: string
return crypto
.createHmac('sha256', webhookSecretKey)
.update(payload, 'utf8')
.digest('hex');
}
// Example usage:
const payload = JSON.stringify({ foo: 'bar' });
const webhookSecretKey = 'your_webhook_secret_key_here';
const signature = generateSignature(payload, webhookSecretKey);
console.log('Signature:', signature);
Example: Verifying HTTP Signature in Node.js
const receivedSignature = req.headers['x-webhook-signature'];
const payload = req.rawBody; // Ensure you get the raw body as a string
const webhookSecretKey = 'your_webhook_secret_key_here';
const expectedSignature = generateSignature(payload, webhookSecretKey);
if (receivedSignature === expectedSignature) {
// Signature is valid
// Process the webhook
} else {
// Invalid signature
// Reject the request
}
Note: Always use the raw request body for signature verification. Any modification (e.g., parsing and re-stringifying JSON) may result in signature mismatch.
Security Best Practices
- Keep your
webhook_secret_key
secure and never expose it publicly. - Rotate your secret keys periodically.
- Always verify the signature before processing the webhook payload.
For more details, refer to your API provider's documentation on webhook security and signature verification.