make_webhook_validation_dependency

View as MarkdownOpen in Claude

Build a FastAPI dependency that validates the X-SignalWire-Signature header (or the X-Twilio-Signature alias) on a route. Attach the returned callable with Depends() to enforce signature validation before your handler runs. The dependency reads and stashes the raw request body, reconstructs the public URL, and calls validate_webhook_signature. On an invalid signature it aborts the request with HTTP 403; on success it returns None so the handler runs normally.

When reconstructing the URL, the dependency honors the SWML_PROXY_URL_BASE environment variable first (highest priority), then the X-Forwarded-Proto / X-Forwarded-Host headers when trust_proxy is True, and finally the URL FastAPI sees.

Parameters

signing_key
strRequired

Your Signing Key from the Dashboard. Required and non-empty — an empty value raises ValueError at construction time.

trust_proxy
boolDefaults to False

If True, honor the X-Forwarded-Proto / X-Forwarded-Host headers when reconstructing the URL. Defaults to False because proxy headers are spoofable.

Returns

Callable — an async FastAPI dependency that validates the signature header and aborts with 403 on failure, returning None on success.

Example

1from fastapi import FastAPI, Depends, Request
2from signalwire.core.security import make_webhook_validation_dependency
3
4app = FastAPI()
5
6validate = make_webhook_validation_dependency(signing_key="PSK_your_signing_key")
7
8@app.post("/webhook", dependencies=[Depends(validate)])
9async def webhook(request: Request):
10 # Reaches here only when the signature is valid.
11 raw_body = request.state.raw_body # bytes; re-parse if you need JSON
12 return {"ok": True}