webhook signature verification

Webhook Signature Verification for SaaS Events

Verify a webhook using the provider’s signing rules, the original request bytes, and the correct endpoint signing secret. Reject failed checks before any business action, including updating subscriptions, sending emails, or granting account access.

Webhook signature verification establishes that the signed content matches what a holder of the signing secret sent. However, it doesn’t establish that an event is new or safe to process twice.

Start by matching the provider’s format, then build verification into your intake path.

Key Takeaways

  • Preserve the original request body before JSON parsing or other transformations.
  • Follow each provider’s headers, signed-message format, and timestamp rules.
  • Compare HMAC digests with a constant-time comparison.
  • Acknowledge verified events only after durable storage.
  • Handle duplicate events and business actions separately from signature verification.

Match the Provider’s Signing Format

An HMAC combines a secret key and message bytes to produce an authentication code. Your server recomputes that code and compares it with the received signature.

Providers differ in which bytes they sign, how they encode the result, and which headers carry it.

GitHub signs the request body

GitHub’s X-Hub-Signature-256 header contains sha256= followed by a hexadecimal HMAC-SHA-256 digest. Compute that digest using your configured webhook secret and the original payload bytes.

GitHub’s delivery validation documentation describes this format and recommends constant-time comparison before further processing.

Stripe includes a signed timestamp

Stripe sends a Stripe-Signature header containing a t= timestamp and signatures such as v1=. Its signed message combines the timestamp, a period, and the raw body.

Use Stripe’s official library rather than adapting a GitHub verifier. The library handles Stripe’s header structure, supported signature scheme, and timestamp validation.

Likewise, a hexadecimal digest from one provider can’t automatically replace another provider’s encoded signature.

Preserve the Raw Body Before Parsing JSON

Signatures depend on exact bytes. Parsing JSON and then calling JSON.stringify() can change whitespace, escaping, or property order while preserving the same application data.

That reconstructed JSON can produce a different HMAC.

Capture the raw body at the webhook route before general JSON middleware runs. In Express, route-specific express.raw({ type: "application/json", limit: "1mb" }) produces a Buffer; register that route before app.use(express.json()). The size limit here is an application choice.

Stripe’s webhook setup example passes the raw body, signature header, and endpoint secret directly into its library.

Also preserve signature headers through your proxy or serverless gateway. Request-body parsing, text conversion, and encoding changes are common sources of mismatches.

For no-code workflows, access to parsed fields alone isn’t enough for a verifier that requires original bytes.

Code Example: Verify GitHub Signatures in Node.js

This Node.js helper accepts a raw Buffer and the X-Hub-Signature-256 header value. Load the environment variable from server-side secret storage.

import { createHmac, timingSafeEqual } from "node:crypto";


const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret) throw new Error("Missing webhook secret");


export function verifyGitHub(rawBody, signature) {
  if (!Buffer.isBuffer(rawBody)) return false;


  if (
    typeof signature !== "string" ||
    !/^sha256=[a-fA-F0-9]{64}$/.test(signature)
  ) {
    return false;
  }


  const expected = createHmac("sha256", secret)
    .update(rawBody)
    .digest();


  const received = Buffer.from(signature.slice(7), "hex");


  return received.length === expected.length &&
    timingSafeEqual(received, expected);
}

The format check rejects missing or malformed headers. Next, createHmac() calculates the digest over untouched bytes. Decoding the received hexadecimal signature produces a comparable byte buffer.

The length guard matters because timingSafeEqual() requires equal-length inputs. Unlike ordinary string equality, this function avoids content-dependent comparison timing. However, the Node.js crypto documentation warns that surrounding code can still introduce timing problems.

Call this helper before parsing the body or invoking business handlers. A false result must end the request without processing.

This example implements GitHub’s format only. It doesn’t add timestamp validation or duplicate detection.

Validate Timestamps to Reduce Replay Risk

A captured request can retain a valid signature. Without freshness controls, an attacker could resend it later without knowing the secret.

Authenticate the timestamp

A useful freshness check requires a timestamp covered by the signature. An unsigned date header offers no reliable proof because an attacker can replace it.

For providers with signed timestamps, perform both cryptographic verification and the documented age check. Neither check substitutes for the other.

Apply the provider’s tolerance

Stripe’s libraries use a default timestamp tolerance of five minutes. Its webhook security guidance also explains that a tolerance of zero disables the recency check.

Keep server clocks synchronized. Otherwise, genuine deliveries can fail timestamp validation.

Stripe generates a fresh timestamp and signature for retries, so an older business event can arrive with a fresh delivery signature. Judge delivery freshness using the signed delivery timestamp, not the event’s creation time.

A timestamp window limits how long a captured delivery remains acceptable. It doesn’t stop repeated deliveries within that window.

Step-by-Step Implementation Checklist

Build the endpoint in this order:

  1. Select the provider configuration. Resolve the endpoint, environment, secret reference, and tenant association through trusted server-side configuration.
  2. Capture the original bytes. Apply a request-size limit and preserve the required signature headers before parsing.
  3. Run the provider’s verifier. Prefer its maintained SDK. Otherwise, reproduce its message format, algorithm, encoding, and constant-time comparison exactly.
  4. Apply supported freshness checks. Require and validate signed timestamps where the provider’s protocol includes them.
  5. Parse and validate the event. After signature verification, validate expected field types, supported event types, and account associations.
  6. Commit durable intake. Store the verified event and processing job atomically, or use an equivalent durable handoff.
  7. Acknowledge acceptance. Return the provider-appropriate success response after storage succeeds, then let workers perform business actions.

Signature verification doesn’t authorize every action described in a payload. Bind the event to the configured integration and its permitted account.

Also, keep verification middleware ahead of generic event routers. Otherwise, a handler might act on an event before the security check finishes.

Store and Rotate Signing Secrets Safely

A signing secret belongs on your server. Anyone who obtains it can generate signatures your verifier accepts.

Separate secrets by purpose and environment

Use a managed secret store or protected server-side deployment configuration. Restrict access to the webhook service and authorized operators.

Keep development and production secrets separate. Stripe endpoint signing secrets are distinct from API keys, and rotating an outbound API credential doesn’t automatically change inbound webhook verification.

For Stripe CLI-forwarded events, use the signing secret printed by the CLI rather than a Dashboard endpoint’s secret.

Rotate with a controlled overlap

Where the provider supports overlapping signing secrets, deploy verification support for the replacement while retaining the valid old secret temporarily.

Test a legitimate delivery under the replacement, migrate all endpoint instances, and then retire the old secret. Keep overlap bounded and record secret references rather than values.

If a secret is compromised, shorten that transition according to your incident response needs. Never restore an exposed secret simply to recover availability.

Separate Verified Intake From Idempotent Processing

Signature verification answers whether a delivery is authentic and unchanged. Idempotency prevents repeated delivery from repeating a business effect.

After verification, enforce a database uniqueness constraint on the provider event ID within its source and tenant scope. Use trusted integration context for that scope.

Commit the event and its processing job together. If storage fails, return a failure response rather than acknowledging an in-memory task that could disappear during a restart.

Workers then handle provisioning or notifications. A success response confirms durable acceptance, not completion of every downstream action.

Protect business operations separately because different events can describe the same operation. For example, a paid invoice should grant its entitlement once even if several related billing events arrive.

Also account for ordering. Before acting on a delayed payment-failure event, retrieve the current invoice state when needed. A newer successful payment may already have resolved the problem.

Test Rejection Paths and Diagnose Failures

A valid delivery proves only the happy path. Tests must also show that rejected requests never reach business processing.

Exercise valid and invalid deliveries

Begin with provider sandbox deliveries or documented fixtures. Then change one body byte while keeping the original signature. Verification must fail.

Also test a wrong secret, missing header, malformed signature, and middleware that parses the body too early. For timestamp-based protocols, test expired timestamps and altered timestamp values.

Separately, submit a valid event twice and concurrently. It should pass signature verification both times but produce one business effect. Simulate a disconnect after durable intake to exercise that boundary.

Fail closed without leaking sensitive data

Return a generic client-error response for missing or invalid signatures. Don’t acknowledge failed verification with a success status.

Treat infrastructure failures differently. If the secret store or durable intake is unavailable, return a server-error response rather than misclassifying the event as an authentication failure.

Log a request identifier and safe categories such as signature_missing, signature_mismatch, or timestamp_expired. Avoid secrets, complete signature values, and unnecessary payload data.

Repeated failures after deployment often point to the wrong endpoint secret, altered bytes, or missing headers.

Frequently Asked Questions

Does HTTPS replace webhook signature verification?

No. HTTPS protects transport, but a public webhook endpoint can still receive requests from other senders. Signature verification authenticates the signed content using the provider’s agreed mechanism.

Can a no-code automation receive signed webhooks safely?

Yes, when its intake path preserves the required bytes and applies the provider’s verification rules before actions run. If those capabilities aren’t available, place a verification endpoint ahead of the automation and forward only authenticated events through a protected connection.

Make Verification the Gate Before Processing

A dependable webhook endpoint preserves raw bytes, follows the provider’s signing contract, and rejects failed checks before business actions begin.

Then durable intake and idempotent workers protect against crashes, retries, and duplicate effects. Together, these controls let authentic SaaS events reach your application without treating every delivery as a new business operation.

About the author

The SAAS Podium

View all posts

Leave a Reply

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