A webhook is how an external service like GitHub or Stripe tells your API that something new happened — but anyone who knows the URL can send a forged request. The fix is to verify the HMAC-SHA256 signature: the sender signs the exact raw bytes of the body with a shared secret, the server recomputes the signature over the body it just received and compares it in constant time. Only when the signatures match do you parse the JSON and handle the event — this works for any webhook that uses a shared secret.

The Problem

Say you write an endpoint that receives GitHub webhooks and checks the signature in the X-Hub-Signature-256 header. Many people parse the JSON first, then dump it back to compute the signature — and that is exactly where it breaks.

import hashlib
import hmac
import json
from fastapi import FastAPI, Request
app = FastAPI()
SECRET = "bi-mat-webhook" # thực tế lấy từ biến môi trường
@app.post("/webhook")
async def webhook_wrong(request: Request):
payload = await request.json()
# SAI: json.dumps() sắp xếp lại key và khoảng trắng,
# chữ ký tính ra khác với chữ ký của bên gửi
body = json.dumps(payload).encode()
digest = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
signature = request.headers.get("X-Hub-Signature-256", "")
if digest != signature.replace("sha256=", ""):
return {"error": "Chu ky khong hop le"}
return {"ok": True}

This approach fails in three ways. First, json.dumps() does not reproduce the original bytes exactly: key order and whitespace can differ, so the computed signature does not match — and valid webhooks get rejected. Second, comparing with != leaks a timing attack: an attacker measures response times to guess the signature one character at a time. Third, returning an error dict with status 200 makes the sender think the webhook was accepted, while the event was never processed at all.

The Solution

The correct way: read the raw body first, compute the signature over exactly those bytes, compare with hmac.compare_digest, and only parse the JSON after the signature matches.

import hashlib
import hmac
import os
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
SECRET = os.environ["WEBHOOK_SECRET"] # không hardcode secret
@app.post("/webhook")
async def webhook(request: Request):
body = await request.body() # đúng từng byte thô bên gửi đã ký
signature = request.headers.get("X-Hub-Signature-256", "")
expected = "sha256=" + hmac.new(
SECRET.encode(), body, hashlib.sha256
).hexdigest()
if not hmac.compare_digest(expected, signature):
raise HTTPException(status_code=401, detail="Chu ky khong hop le")
payload = await request.json() # chỉ parse SAU khi chữ ký đã khớp
print("Nhan su kien:", payload.get("action"))
return {"ok": True}

Why does this work? request.body() returns exactly the bytes the sender signed, so the recomputed signature always matches when the secret is right — regardless of key order or whitespace. hmac.compare_digest compares in constant time, so it leaks nothing through response timing. The secret comes from an environment variable instead of being hardcoded, and an authentication failure returns 401. One caveat: if an endpoint declares both Request and a Pydantic model, FastAPI still parses the body first — so it is best to accept only Request and parse it yourself after verification.

Apply It to Your Project

Apply this right away to every webhook you run without signature verification: write a verification dependency once and attach it to every webhook endpoint with Depends — write once, reuse everywhere. For sensitive webhooks like payments, also check the timestamp in the header (the Stripe way): reject requests whose timestamp is more than 5 minutes off to block replay attacks. Finally, log every failed verification together with the source IP so you can spot who is probing your endpoints.

Related Posts

Frequently Asked Questions

Why can’t I parse the JSON and dump it back to compute the signature?

Because JSON is flexible: the same data can be written as many different byte strings. The sender signs the original byte string, so dumping it back with even one different space already breaks the signature; computing over the raw body never drifts.

Does comparing with == really matter — the signature is so short?

Yes. The == operator stops at the first differing character, so response time reveals where the mismatch is; an attacker measures repeatedly to guess the whole signature bit by bit. hmac.compare_digest always walks the full string, so it leaks none of that information.

What if the signature header has a different name on each service?

Each service names it differently — GitHub uses X-Hub-Signature-256, Stripe uses Stripe-Signature — but the principle is the same: read that exact header, compute the HMAC over the raw body, and compare in constant time.

💬 Have you tried this in your own project? If you hit an error or know a shorter way, leave a comment below — I read them all and will add the best ideas to the post.

References