Skip to main content

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.

FastAPI Middleware for Real-time Identity Risk Scoring with Didit

Contents

In this guide

Jump to the part you need.

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:

  • Core KYC: Get started with essential identity verification 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.

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

Blog questions

Who writes the Didit blog?
The Didit team. Guides reviewed by Alberto Rosas, co-founder and CEO, carry his byline. The rest are published as Didit.
Which topics does the blog cover?
Eight topics: ID verification, business verification (KYB), AML, sanctions and compliance, fraud prevention, transaction monitoring and crypto, country guides, agents and developers, and product updates.
Is the blog available in my language?
Yes, in 15 languages: English, Spanish, French, German, Brazilian and European Portuguese, Catalan, Russian, Arabic, Chinese, Japanese, Hindi, Indonesian, Korean and Swahili. Not every post is translated, so each language shows the posts it has.
Where do I find product updates?
In the changelog at /changelog/ and under the Product updates topic.
Are these posts legal advice?
No. Regulation posts explain rules; your legal team decides how they apply.
How do I find posts on one topic?
Open one of the eight topics, or search the blog.
Are posts dated?
Yes. Every post shows when it was published and when it was last updated.
Do posts link to the docs?
Developer posts link to the matching page on docs.didit.me and to the API reference.
Is the blog the same as the docs?
No. The blog explains rules, markets and product changes for a general reader, while docs.didit.me holds the integration guides and the API reference. Developer posts link the matching docs page and the API reference they describe.

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.