Cybersecurity 5 min read

Secure Webhooks: How to Validate Signatures and Prevent Duplicate Processing

Learn how to secure webhooks with HTTPS, signature validation, payload verification, and idempotency to build reliable application integrations.

Secure Webhooks: How to Validate Signatures and Prevent Duplicate Processing

Webhooks enable two applications to notify each other when an event occurs. For example, a payment service sends a notification after a transaction status changes, or a project management platform alerts another application when a task is updated. The recipient does not need to continuously poll the source service for updates. However, because webhooks are typically received via network endpoints, applications must ensure messages genuinely originate from legitimate providers and avoid processing the same event multiple times.

What are webhooks and what are the risks?

A webhook is an HTTP request automatically sent to a recipient URL when a specific event occurs. The message may contain the event identifier, timestamp, changed object, and data required by the application. Implementations that accept JSON without authentication risk processing forged messages. Meanwhile, providers may resend notifications when the recipient server responds slowly or the connection drops. Therefore, authenticity validation and duplicate handling must be designed together.

Use HTTPS and dedicated endpoints

Deploy webhook endpoints on HTTPS so traffic is encrypted in transit and clients can verify the recipient server. Provide dedicated routes, limit accepted HTTP methods, and set maximum request sizes and processing timeouts. Error responses should not leak tokens, secrets, or internal details. If the provider supplies a stable list of source IP addresses, network rules can serve as an additional layer, but IP lists do not replace signature validation and need updating when infrastructure changes.

Validate signatures correctly

Many webhook providers include a cryptographic signature in the header. The recipient computes the expected value using the message body and shared secret, then compares it against the received signature. Follow the provider’s documentation regarding algorithms, header formats, encoding, and whether timestamps are included in the signature. If an official library is available, use it rather than implementing the algorithm yourself.

Another important point is to validate the raw request body bytes if that is what the provider uses to create the signature. Parsing JSON and re-serializing it can alter whitespace, field order, or encoding, causing the computed result to differ. Do not accept a message merely because the signature header exists; the computation and verification must actually succeed.

Use a timing-safe signature comparison, according to the capabilities of your language or library. Store secrets in a secret manager or server configuration with restricted access, not in source code, repositories, or logs. Prepare a rotation process if secrets are suspected to be compromised. If the provider supports multiple secrets during rotation, follow their official procedure so the transition does not break the integration.

Check timestamps and prevent replay attacks

A valid signature proves the message was created by a party knowing the secret, but does not always prove the message is recent. An attacker who obtains a copy of an old request might attempt to resend it. If the provider includes a timestamp or sequence number, verify it according to their specification and reject messages outside the allowed time window. Do not create your own timing rules without checking the provider’s official tolerance, because server clock differences can cause legitimate messages to be rejected.

For additional protection, store unique event identifiers or delivery IDs. Before processing a message, check whether that ID has been received before. Store idempotency records atomically in appropriate storage, with unique indexes or transaction mechanisms so two concurrent requests cannot both pass the check.

Implement idempotency to prevent duplicate processing

An operation is called idempotent if repeating the same request does not duplicate the final effect. For example, a payment system must not add balance twice simply because the same transaction notification was resent. Use the provider’s event ID as the idempotency key if available. Record processing status and results, then ensure business data changes and event marking are handled consistently. If lengthy work is done through a queue, mark messages with clear status and make workers safe against redelivery.

Avoid the simple pattern of “check ID, then save ID” without concurrency protection. Two workers might check at nearly the same time and both conclude the message has not been processed. Database unique constraints or atomic transactions help close this gap. Also define ID retention periods based on the provider’s retry policy and business requirements.

Responses, logging, and monitoring

HTTP responses should follow provider guidelines. Generally, the recipient needs to return a success response after the message is safely received for processing, not after all background work completes. However, do not send a success response before the message is reliably stored, because subsequent failures could cause the event to be lost. For heavy processing, save the message to a queue first, then work asynchronously.

Log reception time, event ID, validation results, processing duration, and error types. Avoid logging secrets, tokens, payment data, or entire payloads unless necessary. Monitor spikes in invalid signatures, excessive retries, queue backlogs, and processing failures. Test scenarios with forged messages, wrong signatures, expired timestamps, duplicate IDs, and simultaneous deliveries in your testing environment.

Pre-launch checklist

  • Endpoint accepts only required methods and request sizes.
  • Signature is computed following provider documentation and raw request body.
  • Timestamp or replay protection is checked if supported.
  • Event ID is stored with concurrency-safe idempotency mechanism.
  • Secrets are stored securely and have rotation procedures.
  • Logs do not contain credentials or unnecessary sensitive data.
  • Retries, network failures, and parallel processing have been tested.

Conclusion

Secure webhooks require more than just an HTTPS endpoint. Signature validation helps verify message authenticity, timestamp checks can limit replay attacks, and idempotency prevents business effects from occurring multiple times due to redelivery. Combine these controls with reliable storage, logs that do not leak secrets, and failure testing. Always follow the official provider documentation because signature formats, headers, and retry policies vary.

References: GitHub Docs: Validating webhook deliveries and Stripe Docs: Webhooks.

Bagikan artikel ini

No comments yet

    Leave a comment

    Your email address will not be published. Required fields are marked *