HMAC combines a shared secret with a hash function to authenticate a message. For webhooks, the provider signs the bytes it sends and your application computes the expected value before trusting the event.
import hashlib
import hmac
def assinatura_valida(corpo: bytes, recebida: str, segredo: bytes) -> bool:
esperada = hmac.new(segredo, corpo, hashlib.sha256).hexdigest()
return hmac.compare_digest(esperada, recebida)
payload = b'{"evento":"pedido.criado"}'
print(assinatura_valida(payload, "digest-recebido", b"segredo"))
Follow the provider's exact algorithm and format, which may include a prefix or timestamp in the signed message. Read the raw body before parsing and load the secret through protected configuration. Never log the secret or complete signature header.
Practical guidance
Use hmac.compare_digest() to reduce timing leakage. Reject missing or malformed signatures before processing. Mitigate replay by enforcing a time window and storing consumed event IDs. Rotate secrets with a controlled overlap that temporarily accepts the previous key.
Learn the underlying digest in hashlib and file integrity. The API security guide covers authorization, limits, and safe logging.
The official hmac documentation, accessed July 22, 2026, documents the API and its constraints.