Guides
Webhook Security Best Practices
A practical checklist for securing webhook endpoints that receive SMS, RCS, WhatsApp and voice events, with clear labels for what is recommended practice and what needs confirmation for your account.
- Author
- By TXTPro Editorial Team
- Published
- Updated
- Reading time
- 11 min read
Why do webhook endpoints need protection?
A webhook endpoint is a public URL that changes data in your systems. Without protection, anyone who discovers it could mark messages as delivered, inject fake replies into your support queue, or flood it with requests. Events also carry personal data such as phone numbers and customer replies.
Recommended practice vs confirmed functionality
The table separates practices you should apply on your side from features that depend on how webhooks are configured for your account. No row in this table describes confirmed TXTPro functionality; anything marked “requires confirmation” is agreed during onboarding. This guide does not claim that TXTPro signs callbacks with HMAC.
| Control | Status | Notes |
|---|---|---|
| HTTPS / TLS on your endpoint | Recommended practice | Required on your side. Whether non-HTTPS URLs are refused is confirmed during onboarding. |
| Request authentication | Requires confirmation | The method (signature, token or other) depends on how webhooks are configured for your account. |
| HMAC-SHA256 signature verification | Recommended where supported | Signing availability, header name and secret exchange require confirmation for your account. |
| Raw-body verification and constant-time comparison | Recommended practice | Applies whenever a signature is provided. |
| Secret rotation | Recommended practice | Rotation procedure requires confirmation. |
| Replay protection and timestamp validation | Recommended where supported | Depends on the sender including a signed timestamp. |
| Idempotency and duplicate handling | Recommended practice | Always implement; senders may retry the same event. |
| Request size limits and rate limiting | Recommended practice | Configure on your endpoint or gateway. |
| Source IP allowlisting | Recommended where supported | Possible only if published source addresses are confirmed for your account. |
| Safe logging | Recommended practice | Your responsibility; never log secrets, OTPs or message content. |
| Queue processing | Recommended practice | Acknowledge quickly and process asynchronously. |
| Sender retries and backoff | Requires confirmation | Retry count, interval and timeout are confirmed during onboarding. |
| Dead-letter queue, monitoring and alerting | Recommended practice | Build on your side for events that cannot be processed. |
HTTPS and TLS
- Serve the endpoint only over HTTPS with a valid certificate from a trusted authority, and renew it automatically.
- Disable outdated TLS versions on your server or load balancer.
- Do not put secrets or tokens in the callback URL query string; URLs end up in logs.
Authentication
Authentication proves a request came from the expected sender. Common methods are an HMAC signature over the body, a shared token in a header, mutual TLS, or source IP allowlisting combined with one of these. Which method applies to your account requires confirmation. Whatever the method, production endpoints should reject requests that fail it with 401 and should refuse to start if the configuration is missing, rather than silently accepting everything.
HMAC-SHA256 signature verification
With HMAC signing, the sender computes a keyed hash of the request body using a shared secret and sends it in a header. Your endpoint repeats the calculation and accepts the request only if the values match. HMAC-SHA256 is a common choice; whether it is available, the header name and how the secret is exchanged require confirmation for your account.
Verify the raw request body
Compute the signature over the exact bytes received. Parsing JSON and re-serialising it can change whitespace or key order and break verification. In Express use express.raw() on the webhook route; in FastAPI use await request.body().
Use a constant-time comparison
Ordinary string comparison can leak timing information. Use crypto.timingSafeEqual in Node.js or hmac.compare_digest in Python.
# Constant-time HMAC-SHA256 verification over the raw request body (Python).
import hashlib
import hmac
def is_valid(secret: str, raw_body: bytes, received: str) -> bool:
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received)
Secret storage and rotation
- Store signing secrets in environment variables or a secrets manager, never in source code or client-side apps.
- Use different secrets for staging and production.
- To rotate without downtime, accept both the current and the previous secret for a short overlap, then remove the old one.
- Rotate immediately if a secret may have been exposed. The rotation procedure for your account requires confirmation.
Timestamp validation and replay attack prevention
A captured, validly signed request could be sent again later. When the sender includes a timestamp inside the signed data, reject requests outside a short tolerance window (for example five minutes). When no signed timestamp is available, deduplication on event ID is your main defence against replays.
// Replay protection and secret rotation pattern (Node.js).
// Use only if the sender includes a signed timestamp; the header name and the
// exact signed string must come from your integration documentation.
import crypto from 'node:crypto';
const TOLERANCE_SECONDS = 300;
const secrets = [process.env.WEBHOOK_SIGNING_SECRET, process.env.WEBHOOK_SIGNING_SECRET_PREVIOUS].filter(Boolean);
function safeEqual(a, b) {
const x = Buffer.from(a, 'utf8');
const y = Buffer.from(b, 'utf8');
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
export function isFresh(timestampSeconds, now = Date.now()) {
const sentAt = Number(timestampSeconds) * 1000;
return Number.isFinite(sentAt) && Math.abs(now - sentAt) <= TOLERANCE_SECONDS * 1000;
}
export function verify(signedPayload, receivedSignature) {
if (typeof receivedSignature !== 'string') return false;
// During rotation, accept the current and the previous secret for a short window.
return secrets.some((secret) =>
safeEqual(crypto.createHmac('sha256', secret).update(signedPayload).digest('hex'), receivedSignature),
);
}
Idempotency and duplicate handling
- Record each event ID under a unique database constraint before processing it.
- If the insert fails because the ID exists, acknowledge with 200 and stop.
- Make status updates idempotent: applying the same event twice must leave the same result.
- Keep processed event IDs at least as long as the sender’s retry window.
Request size limits and rate limiting
- Cap the request body size (for example 64 KB for status events) and reject larger bodies with 413 before reading them fully.
- Apply rate limits at your gateway or load balancer so a flood of requests cannot exhaust your workers.
- Allowlist source IP addresses only if published addresses are confirmed for your account, and keep signature checks in place as well.
- Expose only the webhook path publicly; keep admin and internal routes behind authentication.
Safe logging
- Log event IDs, message IDs, event types, statuses and response codes.
- Mask phone numbers, and never log message text, OTPs, IVR keypresses, signatures or secrets.
- Restrict access to logs, and set retention periods in line with your privacy policy.
Queue processing
Verify, validate and record each event, put it on a queue, and respond. Do database updates, CRM calls and notifications in a separate worker. This keeps response times short, which reduces duplicate deliveries, and means a slow downstream system cannot make your endpoint time out.
Retries, exponential backoff and dead-letter queues
Retry and exponential backoff
Return a 2xx only after an event is safely queued. Where the sender retries on errors, retries typically use increasing delays. Inside your own system, retry failed processing with exponential backoff (for example 1, 2, 4, 8 seconds, with random jitter) and a cap on attempts.
Dead-letter queue
Move events that still fail after the final attempt to a dead-letter queue with the error reason, so they can be inspected and replayed instead of being lost.
Monitoring and alerts
Track request rate, verification failures, response times, queue depth and dead-letter volume. Alert when events stop arriving during sending hours, when verification failures spike (a possible attack or a rotated secret), or when the dead-letter queue grows.
Webhook security checklist
- HTTPS endpoint with a valid certificate
- Signature (or confirmed alternative) verified over the raw body, with a constant-time comparison
- Receiver refuses to start without its authentication configuration
- Timestamp tolerance check, where a signed timestamp is provided
- Payload validation, body size limit and rate limiting
- Event ID deduplication with a unique constraint
- Queue first, acknowledge fast, process asynchronously
- Secrets in a secrets manager, with a rotation plan
- Safe, access-controlled logs
- Dead-letter queue, monitoring and alerts
Complete receivers that apply these controls are in the Node.js webhook guide and the Python webhook guide. Channel specifics are covered in the webhook integration hub.
Frequently asked questions
What is HMAC webhook signing?
HMAC signing means the sender hashes the request body with a shared secret and sends the result in a header. The receiver recomputes the hash and accepts the request only if both values match, which proves the sender knew the secret and the body was not changed.
Are TXTPro webhooks signed?
Signing availability, the header name and the secret exchange process depend on how webhooks are configured for your account and are confirmed during onboarding. Your endpoint should not accept unauthenticated callbacks in production.
Is IP allowlisting enough to secure a webhook?
No. Use allowlisting only where published source addresses are confirmed, and keep signature or token verification in place, because IP ranges can change and can be shared.
Should I return an error when I receive a duplicate event?
No. Acknowledge duplicates with a 2xx response so the sender stops retrying, but do not process them again.
Sources and further reading
Editorial note: This article is written by the TXTPro editorial team (KSVL Solutions) for general information. Regulations and platform policies change; check the linked official sources and seek professional advice for your situation. See our editorial standards.
