Securing Webhooks with Cloudflare Workers: A Didit Integration Guide
Learn how to build a robust and secure webhook endpoint for Didit identity verification using Cloudflare Workers. This guide covers HMAC signature verification, timestamp validation, and best practices to protect your.

Enhanced Security with Cloudflare WorkersCloudflare Workers provide an ideal serverless environment for securely processing webhooks, offering edge-level protection and efficient signature verification.
HMAC Signature Verification is CrucialAlways verify the HMAC-SHA256 signature of incoming webhooks to ensure their authenticity and integrity, preventing unauthorized data injection or tampering.
Timestamp Validation Mitigates Replay AttacksImplement timestamp checks to ensure webhook requests are fresh, guarding against replay attacks where old, legitimate requests are resent by malicious actors.
Didit Simplifies Secure Identity VerificationDidit’s AI-native platform provides robust, real-time webhook notifications for all identity verification products, ensuring secure and reliable data delivery for your applications.
In today's interconnected digital landscape, webhooks are a cornerstone of real-time communication between services. They enable instant notifications for events like identity verification outcomes, payment confirmations, and user activity. However, the convenience of webhooks comes with a critical security challenge: ensuring the authenticity and integrity of the data received. Without proper safeguards, your application could be vulnerable to spoofing, tampering, or replay attacks.
This guide will walk you through building a secure webhook endpoint for Didit identity verification using Cloudflare Workers. Cloudflare Workers offer a powerful, serverless platform at the edge, ideal for processing and securing webhooks with minimal latency and maximum reliability. Didit, as an AI-native identity platform, relies on secure webhooks to deliver real-time KYC notifications, making this integration crucial for any business leveraging Didit’s robust identity verification solutions.
Why Secure Your Webhooks?
Imagine receiving a webhook notification that falsely claims a user has passed ID Verification, when in reality, they failed. Or perhaps a malicious actor replays an old, legitimate webhook to trigger an action in your system multiple times. These scenarios highlight the critical need for webhook security.
The primary threats to webhook endpoints include:
- Spoofing: An attacker sends a fake webhook, pretending to be Didit, to trick your system into taking unauthorized actions.
- Tampering: An attacker intercepts a legitimate webhook and modifies its payload before it reaches your server.
- Replay Attacks: An attacker captures a legitimate webhook and resends it later to trigger the same action again, potentially leading to duplicate transactions or other issues.
Securing your webhooks involves verifying the sender's identity and ensuring the data hasn't been altered. Didit provides a robust mechanism for this through HMAC-SHA256 signatures and timestamp validation, which we will implement in our Cloudflare Worker.
Setting Up Your Didit Webhook Secret
Before you can verify Didit webhooks, you need your unique Webhook Secret Key. This key is paramount for cryptographic signature verification. Here's how to retrieve it:
- Log in to your Didit Console.
- Navigate to Settings → API Keys.
- Copy your Webhook Secret Key.
This secret key should be stored securely and never exposed publicly. For Cloudflare Workers, it's best to store it as a Worker secret or an environment variable.
Building a Secure Cloudflare Worker for Didit Webhooks
Cloudflare Workers are JavaScript, TypeScript, or WebAssembly applications that run on Cloudflare's global network, close to your users. This makes them incredibly fast and scalable for handling incoming webhook requests. Here’s a step-by-step guide to creating a Worker that securely processes Didit webhooks.
1. Create Your Cloudflare Worker
First, set up a new Cloudflare Worker project. You can do this using the wrangler CLI tool:
npx wrangler generate didit-webhook-handler
cd didit-webhook-handler
2. Add Your Didit Webhook Secret as a Cloudflare Secret
To keep your webhook secret secure, add it as a secret to your Worker:
npx wrangler secret put DIDIT_WEBHOOK_SECRET
When prompted, paste your Webhook Secret Key from the Didit Console.
3. Implement Webhook Logic in index.js
Your Worker's index.js file will contain the logic for receiving, validating, and processing Didit webhooks. The core steps are:
- Read Raw Request Body: The HMAC signature is generated from the raw request body, so it's crucial not to parse it before verification.
- Verify HMAC-SHA256 Signature: Compare the signature provided in the
X-Signatureheader with a signature you generate using yourDIDIT_WEBHOOK_SECRETand the raw request body. - Validate Timestamp: Check the
X-Timestampheader to ensure the request is recent (e.g., within 5 minutes) to prevent replay attacks. - Parse JSON and Process: If verification passes, parse the JSON body and handle the identity verification result.
Here’s a basic example of the Worker code:
import { createHmac } from 'crypto'; // Cloudflare Workers provide 'crypto' module
export default {
async fetch(request, env, ctx) {
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
const diditWebhookSecret = env.DIDIT_WEBHOOK_SECRET;
if (!diditWebhookSecret) {
return new Response('Webhook secret not configured', { status: 500 });
}
const signature = request.headers.get('X-Signature');
const timestamp = request.headers.get('X-Timestamp');
const rawBody = await request.text();
if (!signature || !timestamp || !rawBody) {
return new Response('Missing required webhook headers or body', { status: 400 });
}
// 1. Validate Timestamp (e.g., within 5 minutes)
const FIVE_MINUTES_IN_SECONDS = 300;
const currentTimestamp = Math.floor(Date.now() / 1000);
if (Math.abs(currentTimestamp - parseInt(timestamp, 10)) > FIVE_MINUTES_IN_SECONDS) {
return new Response('Webhook timestamp too old or in the future', { status: 403 });
}
// 2. Verify HMAC-SHA256 Signature
const expectedSignature = createHmac('sha256', diditWebhookSecret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
if (expectedSignature !== signature) {
return new Response('Invalid webhook signature', { status: 403 });
}
// 3. Process the webhook payload
try {
const payload = JSON.parse(rawBody);
// Log or process the payload, e.g., update user status in your database
console.log('Received Didit webhook:', payload);
// Example: Accessing verification status
if (payload.event === 'session.completed' && payload.data.status === 'approved') {
console.log(`User ${payload.data.vendor_data} successfully verified.`);
// Trigger further actions like granting access or updating user profile
}
// Didit offers various products like ID Verification, Passive & Active Liveness, and AML Screening.
// The webhook payload will reflect results from these checks.
return new Response('Webhook processed successfully', { status: 200 });
} catch (error) {
console.error('Error parsing webhook body:', error);
return new Response('Error parsing JSON payload', { status: 400 });
}
},
};
4. Deploy Your Worker
Once your code is ready, deploy it to Cloudflare:
npx wrangler deploy
After deployment, Cloudflare will provide you with a URL for your Worker. This is the endpoint you'll configure in your Didit Console for receiving webhooks.
Configuring Didit to Send Webhooks
With your secure Cloudflare Worker deployed, the final step is to tell Didit where to send your real-time notifications:
- Go back to your Didit Console.
- Navigate to Workflows and select the workflow you want to configure (e.g., your KYC workflow that uses Didit's ID Verification and Passive & Active Liveness).
- In the workflow settings, find the Webhook URL configuration.
- Enter the URL of your deployed Cloudflare Worker.
- Save your changes.
Now, whenever an identity verification session completes or its status changes, Didit will send a secure webhook notification to your Cloudflare Worker, which will then validate and process it.
How Didit Helps
Didit is designed with security and developer experience at its core. Our AI-native identity platform provides a modular architecture that allows you to compose complex verification workflows with ease. When it comes to webhooks, Didit simplifies the process by:
- Providing Secure Webhook Notifications: All Didit webhooks are signed with an HMAC-SHA256 signature and include a timestamp, ensuring the authenticity and integrity of the data you receive. This is crucial for products like ID Verification, 1:1 Face Match, and AML Screening, where data accuracy is paramount.
- Real-time Updates: Get instant notifications for every stage of the verification process, allowing your application to react immediately to user verification outcomes.
- Comprehensive Data: Webhook payloads include all the necessary details about the verification session, including the results from various Didit products like Passive & Active Liveness, Phone & Email Verification, and Proof of Address.
- Developer-First Approach: Didit offers an instant sandbox, clear public documentation, and clean APIs, making integration straightforward. Our Free Core KYC tier and pay-per-successful-check model, with no setup fees, make it easy to get started and scale.
By integrating Didit webhooks with a secure Cloudflare Worker, you establish a resilient and trustworthy channel for real-time identity verification updates, protecting your business and your users.
Ready to Get Started?
Ready to see Didit in action? Get a free demo today.
Start verifying identities for free with Didit's free tier.