Webhook Security Best Practices
Essential security practices for handling webhooks: signature verification, replay protection, and idempotency.
Introduction
Webhooks are powerful, but they can also be a security vulnerability if not handled correctly. This guide covers essential security practices.
1. Verify Webhook Signatures
Most webhook providers include a signature header. Always verify it:
const crypto = require('crypto');
function verifySignature(payload, signature, secret) {
const hmac = crypto.createHmac('sha256', secret);
const digest = hmac.update(payload).digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(digest)
);
}
2. Implement Replay Protection
Store and check webhook IDs to prevent replay attacks:
const processedWebhooks = new Set();
app.post('/webhook', (req, res) => {
const webhookId = req.headers['x-webhook-id'];
if (processedWebhooks.has(webhookId)) {
return res.status(200).send('Already processed');
}
processedWebhooks.add(webhookId);
// Process the webhook...
});
3. Make Handlers Idempotent
Design your handlers so they can safely process the same webhook multiple times.
Conclusion
Security is critical when handling webhooks. Follow these practices to protect your application from common attacks.
Written by Skooh Team