Skip to main content

Secure Your Webhooks: HMAC and Key Rotation for Didit Events

Read the raw body, check X-Timestamp within 300 seconds, recompute HMAC-SHA256 with your destination secret, compare in constant time, and rotate the secret with the 24 hour -Previous overlap.

Secure Your Webhooks: HMAC and Key Rotation for Didit Events

Contents

In this guide

Jump to the part you need.

This guide fits teams already receiving Didit events and moving real decisions on them: approvals, declines, AML hits, transactions. It shows how to verify every request with HMAC-SHA256 and rotate a signing secret without dropping events. The live price feed prices completed checks, from $0.33 for a full ID check; it does not publish a webhook-delivery price. The caveat: the simple signature header is deprecated, and a rotated secret stays live for 24 hours.

Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.

Didit webhook signing and rotation at a glance
ItemWhat it is
Signature algorithmHMAC-SHA256 with a per-destination shared secret
Header to verify firstX-Signature-V2, computed over the sorted, Unicode-preserved canonical JSON
Header for exact raw bytesX-Signature, safe only if nothing re-encodes the body
Deprecated headerX-Signature-Simple, authenticates the envelope only, not the decision body
Replay windowReject when the absolute difference from X-Timestamp is more than 300 seconds
Rotation overlap24 hours, via the -Previous headers signed with the replaced secret
Secret locationGET /v3/webhook/destinations/{destination_uuid}/, never in the list response
Published pricingThe live price feed prices completed checks. It does not publish a webhook-delivery line
Event selectionExplicit list, no wildcard. Multiple destinations fan out to different URLs

Start free in the sandbox at business.didit.me, no sales call. Developers who want Didit inside an AI assistant can connect the Didit MCP server and drive the same API from a prompt. Product pricing is public on the pricing page.

What a verified webhook gives you

A signature check answers two questions for each request: Did this come from Didit, and was the body changed in transit? HMAC-SHA256 covers both. It does not prove that you have not seen the request before. Replay handling is separate: reject stale X-Timestamp values, then make state changes idempotent on event_id.

The signing secret is scoped to a webhook destination, so rotation changes one value on one endpoint. Your verification code stays the same apart from accepting the -Previous header during the overlap.

A session overview with its warnings in the Didit Business Console.
The decision object inside a status.updated webhook mirrors this session view, feature by feature.

Before you start

  • A Didit application in the Business Console.
  • An HTTPS endpoint that accepts POST and can read the raw request body before any JSON parser touches it.
  • An API key that can reach the webhook routes, sent as x-api-key to https://verification.didit.me. Keys live under Developers, then API keys, per the API authentication guide.
  • A server-side secret store. An environment variable is enough; a secret manager is better. Never ship the signing secret to a browser or a mobile bundle.
  • A sandbox application, where every check is mocked and nothing is charged. The sandbox guide explains the scenarios and magic values.
  • Python 3 for the example below. It uses only the standard library.

Verify a Didit webhook in eight steps

  1. Create a destination and subscribe to exact event names. A destination is one URL plus the list of events it receives. There is no wildcard, so list every family you need in subscribed_events, for example status.updated, data.updated, user.status.updated, business.status.updated, transaction.created and travel_rule.status.updated. Authentication activity and bank events have their own pages; do not register event types that are not listed in the webhooks guide.
  2. Read the destination and its secret. The list call returns configuration plus 30 day delivery metrics:
    curl -X GET 'https://verification.didit.me/v3/webhook/destinations/' \
      -H 'x-api-key: $DIDIT_API_KEY'
    The list never includes the signing secret, only secret_last4. Fetch the full secret_shared_key from the single destination route:
    curl -X GET 'https://verification.didit.me/v3/webhook/destinations/{destination_uuid}/' \
      -H 'x-api-key: $DIDIT_API_KEY'
    Store it as DIDIT_WEBHOOK_SECRET in your server environment. Keep secret_last4 somewhere visible so the next person can tell which secret is deployed.
  3. Read the raw body. Signature verification needs the bytes Didit sent. If your framework parses JSON first and re-serializes later, key order and whitespace can change and every check fails. Capture the raw body, then parse. Choose the documented mode that matches your framework: X-Signature-V2 uses canonical JSON, and X-Signature uses the exact raw bytes. They are separate modes; do not compare a canonical-JSON header against a raw-byte payload.
  4. Reject stale timestamps. X-Timestamp is Unix epoch seconds from dispatch. Compare it with your server clock and refuse anything older or newer than 300 seconds. This closes the replay window on a captured request.
  5. Recompute and compare in constant time. The function below checks X-Signature-V2 over the canonical JSON and falls back to X-Signature over the raw bytes. It accepts a match on either the current header or its -Previous twin, which is what keeps verification alive during a rotation.
    import hashlib
    import hmac
    import json
    import os
    import time
    
    SECRET = os.environ['DIDIT_WEBHOOK_SECRET'].encode()
    
    
    def canonical_json(raw_body: bytes) -> bytes:
        return json.dumps(
            json.loads(raw_body),
            sort_keys=True,
            separators=(',', ':'),
            ensure_ascii=False,
        ).encode('utf-8')
    
    
    def signature_matches(header_value: str, payload: bytes) -> bool:
        expected = hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, header_value)
    
    
    def verify(headers, raw_body: bytes) -> bool:
        try:
            sent_at = int(headers.get('X-Timestamp', '0'))
        except ValueError:
            return False
        if abs(time.time() - sent_at) > 300:
            return False
    
        candidates = (
            ('X-Signature-V2', canonical_json(raw_body)),
            ('X-Signature', raw_body),
        )
        for name, payload in candidates:
            current = headers.get(name)
            previous = headers.get(name + '-Previous')
            if current and signature_matches(current, payload):
                return True
            if previous and signature_matches(previous, payload):
                return True
        return False
    Use a case-insensitive header mapping, as Flask, Starlette and Express all provide. The snippet compares hex digests.
  6. Route on the event, not on the URL. Parse only after the signature passes. Switch on webhook_type, then on the exact, case-sensitive status string. Note that Kyc Expired uses a single capital K, and In Review contains a space. Treat event_id as an idempotency key: record it, skip repeats, and update state idempotently.
    def handle(headers, raw_body: bytes):
        if not verify(headers, raw_body):
            return 401, 'invalid signature'
        event = json.loads(raw_body)
        event_id = event['event_id']
        webhook_type = event['webhook_type']
        status = event.get('status')
        vendor_data = event.get('vendor_data')
        # Record event_id idempotently, then route on webhook_type and status.
        # The product-specific action is implementation-specific.
        return 200, 'ok'
  7. Answer fast and watch destination health. Return 2xx as soon as the event is recorded, then do the slow work. If a destination starts failing, health_status reports it: failing after 3 or more consecutive first attempts fail, degraded when an attempt failed in the last 24 hours and no later attempt delivered that event, healthy otherwise. Read it from the same list call, alongside failed_deliveries_count and error_rate_percentage.
  8. Rotate with the 24 hour overlap. Rotate the signing secret for the destination in the Business Console. For 24 hours after rotation, Didit also sends X-Signature-V2-Previous, X-Signature-Previous and X-Signature-Simple-Previous, signed with the replaced secret. Deploy the new value, keep accepting either header, then delete the old secret from your store when the window closes. The -Previous headers are never sent for the legacy application webhook_url.

Expected output

A verified session webhook includes event identity and environment, with a decision object on Approved, Declined, In Review and Abandoned. Other event families use their documented payloads. A trimmed status.updated payload looks like this:

{
  "event_id": "6c1f0f43-2a1e-4c8b-9f3a-1d7e0b2c4a11",
  "session_id": "b2f0c3e1-8a44-4d1f-9c2a-77a1d0e5b930",
  "status": "Approved",
  "webhook_type": "status.updated",
  "created_at": 1627680000,
  "timestamp": 1627680000,
  "application_id": "0b6a1c62-5c1f-4b0e-8d0f-3c1f9e2a7d55",
  "environment": "live",
  "sandbox_scenario": null,
  "vendor_data": "your-internal-user-id",
  "decision": {}
}

Your endpoint answers 2xx, for example 200 ok. The decision object mirrors GET /v3/session/{sessionId}/decision/ and carries per-feature arrays: id_verifications[], liveness_checks[], face_matches[], aml_screenings[], poa_verifications[] and the rest, each pinned to a node_id. The schema is documented once in the data models reference.

A rejected request answers 4xx and does nothing else. That distinction is the whole point: no state changes on an unverified body.

AML screening result for a session in the Didit Business Console.
AML results reach your endpoint inside decision.aml_screenings[], the same data shown here in the Console.

Inputs and outputs

What arrives on each request and what you read from it
Field or headerWhereWhat you do with it
X-Signature-V2Request headerHMAC-SHA256 over the sorted, Unicode-preserved canonical JSON. Verify this one first
X-SignatureRequest headerHMAC-SHA256 over the exact raw bytes. Works only if your stack does not re-encode the body
X-Signature-SimpleRequest headerHMAC-SHA256 over {timestamp}:{session_id}:{status}:{webhook_type}. Deprecated, envelope only
X-TimestampRequest headerUnix epoch seconds at dispatch. Reject outside 300 seconds
X-Signature-V2-PreviousRequest headerSignature made with the replaced secret, present for 24 hours after rotation. Accept either
event_idBodyIdempotency key. Store it before you act
webhook_typeBodyRouting value, for example status.updated or transaction.created
statusBodyExact case-sensitive string, from Not Started to Kyc Expired
decisionBodyPresent on Approved, Declined, In Review and Abandoned. Read the plural feature arrays
secret_shared_keyAPI responseThe signing secret. Server-side only, never in a client bundle
health_statusAPI responsehealthy, degraded or failing. Alert on the last two

Failure cases and recovery

What breaks, why, and the shortest way back
SymptomCauseRecovery
Every signature check fails after a framework upgradeThe body was parsed and re-serialized before hashingVerify against the raw bytes with X-Signature, or restore raw body capture and go back to X-Signature-V2
Signature checks fail for a few minutes during a deployThe new secret is live on one side and the old one on the otherAccept a match on the -Previous header. Both signatures are sent for 24 hours after rotation
Valid-looking events rejected as staleServer clock drift, or a timestamp parsed as millisecondsTreat X-Timestamp as epoch seconds and keep the host on NTP. The window is 300 seconds either way
Duplicate approvals or duplicate credit grantsRetries re-deliver an event your handler already processedKey your writes on event_id and make the handler idempotent. Retries are bounded, but a slow endpoint invites them
Envelope verified, decision body untrustedYou verified X-Signature-Simple, which covers the envelope onlyRe-fetch from GET /v3/session/{session_id}/decision/ before acting, or move to X-Signature-V2
No events at all, destination marked failingEndpoint down, blocked address, timeout, or a non-2xx answerCheck failed_deliveries_count and failing_since, fix the endpoint, then resend. Any successful attempt ends the streak
403 on the management callMissing header, a scoped key without webhook access, or an address outside the key IP listUse a key with that access from Developers, then API keys. 429 means back off and retry

The full status list and its transitions are documented in verification statuses. A session in In Review has not been decided yet, so treat that event as pending human review, not as a pass or a fail.

Cost: how webhooks relate to your bill

The live Didit price feed prices completed checks. It does not publish a webhook-delivery price, so do not budget a separate per-delivery line from our published data. What the feed does show is the price of the check that produced the event. The pricing page lists every module, and the machine-readable pricing.json carries the same numbers.

Worked example, list prices, arithmetic shown. Say you run 12,000 full ID checks and 1,500 AML screenings in a month. Billing counts completed checks, not webhook events.

  • 12,000 full ID checks at $0.33 = 12,000 x 0.33 = $3,960.00. That bundle is ID document $0.15 + passive liveness $0.10 + face match 1:1 $0.05 + device and IP analysis $0.03.
  • 1,500 AML screenings at $0.20 = 1,500 x 0.20 = $300.00.
  • Usage at list price = 3,960.00 + 300.00 = $4,260.00.

On Scale, every Didit price is 10% lower. Discounted usage before plan accounting is 3,960.00 x 0.90 = $3,564.00 for full ID checks and 300.00 x 0.90 = $270.00 for AML, so 3,564.00 + 270.00 = $3,834.00. Plan accounting is separate: $3,834.00 discounted usage + $299.00 monthly plan fee - $350.00 monthly credit = $3,783.00 net for this example. The $299 fee and $350 credit are plan terms, not usage prices, and unused monthly credit does not roll over. The Free plan gives $10.00 of monthly credit, and the sandbox costs nothing on any plan.

How Didit Billing Works: Credits, Auto-Recharge & Volume Discounts
Checks consume credit when they complete. The live price feed prices those checks, and plan credit is separate from usage prices.

Three things sit on our side: we sign every request with the destination secret, we retry failed deliveries within a bounded budget, and we publish per-destination health so you can alert on it. We report 4,000+ active customer companies.

Three things stay on yours. Custody of the secret, which is why the list response shows only secret_last4. The decision about what an event means for your product. And the response to a session that lands in In Review, where a person on your side or in the Console has to approve, decline or request a resubmission. No automated signature check makes that call for you.

If you need a governed rotation schedule, put it on your own calendar. Didit documents the 24 hour overlap after a destination secret is rotated; the rotation schedule itself is your own operational policy.

Sources

Next step: open the sandbox, create a destination, and run the verification function against a real signed event before you touch production. No sales call, and nothing charged until a check completes.

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

Questions

Frequently asked questions

Which signature header should I verify on Didit webhooks?

Verify X-Signature-V2 first. It is HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON, so it survives a proxy or framework that re-encodes the body. Keep X-Signature, which hashes the exact raw bytes, as a second check when your stack preserves the payload.

How do I stop replay attacks on a captured webhook?

Reject any request whose X-Timestamp is more than 300 seconds away from your server clock, in either direction. Then store event_id and skip a second write for an id that already exists. Together those two checks make a replayed request harmless.

Where do I find my Didit webhook signing secret?

Call GET /v3/webhook/destinations/{destination_uuid}/ with your x-api-key header. The list route never returns the secret, only its last four characters, so you can tell destinations apart without exposing the value. Store it as a server-side environment variable or in a secret manager.

What happens to webhooks while I rotate the signing secret?

For 24 hours after a destination secret is rotated, Didit sends the normal signature header and a -Previous variant signed with the replaced secret. Accept a match on either one and deploys stop breaking verification. Remove the old secret from your store once the window closes.

Is X-Signature-Simple safe to use?

It is deprecated and it only authenticates the envelope: timestamp, session id, status and event type. The decision body underneath is not covered. If you still verify with it, re-fetch the decision from GET /v3/session/{session_id}/decision/ instead of trusting the payload.

Why does my signature check fail even though the webhook is genuine?

The usual cause is a framework that parses JSON before your handler runs and re-serializes with different key order or whitespace. Capture the raw request body and hash those bytes, or switch to X-Signature-V2, which is computed over canonical JSON. A drifting server clock is the second most common cause.

Do Didit webhook deliveries cost anything?

The published price feed does not list webhook delivery as a priced line. It prices completed checks, such as $0.33 for a full ID check or $0.20 for an AML screening. Plan credit is separate from those usage prices, so read the live feed before you quote a number.

How do I know a webhook destination is failing?

Read health_status from GET /v3/webhook/destinations/. It reports failing after 3 or more consecutive first attempts fail, and degraded when an attempt failed in the last 24 hours and no later attempt delivered that event. The same response carries failing_streak, failing_since and a 30 day error rate.

Does Didit retry a webhook my endpoint rejected?

Yes, delivery uses bounded retries, so a 5xx or a timeout is retried rather than dropped. Because a retry can arrive after you already processed the event, make the handler idempotent on event_id and return 2xx quickly. The retry policy itself is documented in the webhooks guide.

Can I test rotation without touching live users?

Yes. Create a sandbox application, point a destination at your local tunnel and rotate its secret there. Sandbox checks are mocked and nothing is charged, so you can rehearse the deploy, the -Previous window and the rollback before you repeat it on a live destination.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.