Skip to main content
Didit Raises $7.5M to Build the Infrastructure for Identity and Fraud
Didit
Back to blog
Blog · March 6, 2026

FastAPI Middleware for Real-time Identity Risk Scoring with Didit

Implement robust, real-time identity risk scoring in your FastAPI applications using Didit's webhooks. This guide covers setting up secure webhook handling, signature verification, and integrating risk signals into your.

By DiditUpdated
fastapi-middleware-real-time-identity-risk-scoring-didit-webhooks.png

Real-time Risk Scoring is EssentialModern applications demand immediate identity risk assessment to combat fraud and ensure compliance effectively.

Secure Webhook Handling is ParamountImplementing robust signature verification and timestamp checks for incoming webhooks prevents tampering and replay attacks, crucial for maintaining data integrity.

FastAPI Middleware Streamlines IntegrationLeveraging FastAPI's middleware capabilities allows for centralized and efficient processing of asynchronous webhook events, seamlessly integrating with your application's flow.

Didit Powers Intelligent Identity OrchestrationDidit provides the AI-native identity verification and webhook infrastructure, offering real-time notifications and comprehensive risk signals to inform your application's security decisions.

In today's digital landscape, the speed and accuracy of identity verification directly impact an application's security posture and user experience. As businesses scale, the need for real-time risk scoring becomes paramount, allowing for immediate action against fraudulent activities and ensuring compliance with regulatory standards. Integrating an advanced identity verification platform like Didit with your backend, particularly using a modern framework like FastAPI, can significantly enhance your defenses.

This blog post will guide you through building a robust FastAPI middleware to process Didit's webhooks for real-time identity risk scoring. We'll cover secure webhook reception, signature verification, and how to integrate these critical risk signals into your application logic.

The Power of Webhooks for Real-time Identity Signals

Webhooks are a cornerstone of modern asynchronous communication, enabling services to send real-time notifications to other applications when specific events occur. For identity verification, this means that as soon as a user completes a verification step, or a risk assessment is finalized, Didit can immediately inform your application. This real-time feedback is crucial for dynamic risk scoring, allowing you to:

  • Instantly update user profiles: Mark users as verified or flag them for review based on the outcome of ID Verification or AML Screening.
  • Trigger conditional workflows: If a user fails a Liveness detection check or is flagged during AML Screening, you can immediately initiate a deeper review process or block access.
  • Enhance fraud detection: Combine Didit's risk signals, such as IP Analysis or Phone Verification results, with your internal fraud models for a more comprehensive assessment.

Didit's webhooks provide detailed JSON payloads with the results of various verification checks, including those from ID Verification, Passive & Active Liveness, 1:1 Face Match, AML Screening & Monitoring, Proof of Address, and Phone & Email Verification. These rich data points are invaluable for constructing a real-time risk profile for each user.

Securing Your Webhook Endpoint with FastAPI Middleware

Receiving webhooks securely is non-negotiable. Malicious actors could attempt to send fake events or replay old ones, leading to compromised data or incorrect actions. Didit's webhooks include an HMAC-SHA256 signature and a timestamp, which are essential for verifying the authenticity and integrity of each incoming request. FastAPI middleware is an excellent place to implement these security checks centrally.

Here's a conceptual outline of how you'd structure your FastAPI middleware:


import hmac
import hashlib
import time
from fastapi import FastAPI, Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse

WEBHOOK_SECRET = "YOUR_DIDIT_WEBHOOK_SECRET" # Get this from Didit Console -> API Keys

class DiditWebhookSignatureMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if request.url.path == "/api/webhooks/didit":
            signature = request.headers.get("X-Signature")
            timestamp = request.headers.get("X-Timestamp")

            if not signature or not timestamp:
                raise HTTPException(status_code=401, detail="Missing webhook signature or timestamp")

            # 1. Verify Timestamp Freshness (e.g., within 5 minutes)
            try:
                request_time = int(timestamp)
                if abs(time.time() - request_time) > 300: # 300 seconds = 5 minutes
                    raise HTTPException(status_code=401, detail="Webhook timestamp too old or too new")
            except ValueError:
                raise HTTPException(status_code=401, detail="Invalid timestamp format")

            # 2. Reconstruct the signed payload
            body = await request.body()
            signed_payload = f"{timestamp}.{body.decode('utf-8')}"

            # 3. Calculate expected signature
            expected_signature = hmac.new(
                WEBHOOK_SECRET.encode('utf-8'),
                signed_payload.encode('utf-8'),
                hashlib.sha256
            ).hexdigest()

            # 4. Compare signatures
            if not hmac.compare_digest(expected_signature, signature):
                raise HTTPException(status_code=401, detail="Invalid webhook signature")

            # If signature and timestamp are valid, proceed
            request.state.didit_webhook_body = body.decode('utf-8') # Store for later processing
        return await call_next(request)

app = FastAPI()
app.add_middleware(DiditWebhookSignatureMiddleware)

@app.post("/api/webhooks/didit")
async def handle_didit_webhook(request: Request):
    # Webhook body is already verified and available in request.state
    payload = json.loads(request.state.didit_webhook_body)
    # Process payload for risk scoring, update user status, etc.
    print("Received valid Didit webhook:", payload)
    return JSONResponse({"status": "success"})

This middleware ensures that every Didit webhook request hitting your /api/webhooks/didit endpoint is authenticated and fresh before your application logic even sees the payload. This is a critical layer of defense against various attack vectors.

Integrating Real-time Risk Signals into Your Application Logic

Once the webhook payload is verified and parsed, your application can extract the necessary information to update user risk scores or trigger specific actions. Didit's API Full Flow documentation outlines the comprehensive structure of these payloads, including session_id, vendor_data (your internal user ID), and the detailed results of each verification step.

For example, if a user undergoes ID Verification and Liveness Detection, the webhook payload will contain the status of these checks. You might define a risk score based on:

  • Successful ID Verification: Lowers risk score.
  • Failed Liveness Detection: Significantly raises risk score, potentially triggering an account freeze.
  • AML Screening Hit (PEP/Sanctions): High risk, requiring immediate manual review.
  • Disposable Phone Number Detected (from Phone Verification): Moderate risk, might indicate fraudulent intent.

Your webhook handler's job is to interpret these signals and update your internal user state or risk profile accordingly. This could involve updating a user_status field in your database, adding a flag for manual review, or even integrating with a dedicated fraud management system.

How Didit Helps

Didit is the AI-native, developer-first identity platform designed to make real-time identity risk scoring seamless and efficient. Our modular architecture allows you to compose verification workflows that precisely meet your needs, from basic ID Verification to advanced AML Screening and Passive & Active Liveness detection. We provide robust webhook capabilities, ensuring that your applications receive real-time, secure notifications about verification outcomes.

With Didit, you benefit from:

  • Free Core KYC: Get started with essential identity verification at no cost, allowing you to build and test your integration without upfront investment.
  • AI-Native Intelligence: Leverage cutting-edge AI for superior fraud detection, liveness detection, and document analysis, providing accurate risk signals.
  • Developer-First Approach: Clean APIs, comprehensive documentation, and an instant sandbox make integration with frameworks like FastAPI straightforward and fast.
  • Orchestrated Workflows: Define complex verification flows with a no-code engine, allowing you to adapt to evolving risk landscapes without code changes.
  • Global Coverage: Verify identities across the globe with support for diverse document types and regional compliance requirements.

By leveraging Didit's Phone & Email Verification, ID Verification, and AML Screening & Monitoring products, combined with our secure webhook infrastructure, you can build a highly responsive and resilient identity risk scoring system within your FastAPI application. Our platform delivers the real-time data you need to make informed decisions and protect your business.

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.

Infrastructure for identity and fraud.

One API for KYC, KYB, Transaction Monitoring, and Wallet Screening. Integrate in 5 minutes.

Ask an AI to summarise this page
FastAPI Middleware for Real-time Identity Risk Scoring.