python / intermediate
Snippet
Webhook HMAC Signature Verification in Django Request Handlers
Validating incoming webhook payloads using HMAC digests ensures data authenticity and prevents tampering. By comparing hashes using constant-time comparison, request handlers protect against timing attacks while validating requests before processing business logic.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import hmacimport hashlibfrom django.conf import settingsfrom django.http import HttpResponseForbidden, JsonResponsedef verify_webhook_signature(request):signature = request.headers.get('X-Signature-256')if not signature:return HttpResponseForbidden('Missing signature header')expected_hash = hmac.new(settings.WEBHOOK_SECRET.encode(),request.body,hashlib.sha256).hexdigest()if not hmac.compare_digest(signature, expected_hash):return HttpResponseForbidden('Invalid payload signature')return JsonResponse({'status': 'verified'})
django
Breakdown
1
signature = request.headers.get('X-Signature-256')
Extracts the cryptographic signature header sent by the external webhook provider.
2
expected_hash = hmac.new(settings.WEBHOOK_SECRET.encode(), request.body, hashlib.sha256).hexdigest()
Computes an SHA-256 HMAC hash using the secret key and the raw request payload bytes.
3
if not hmac.compare_digest(signature, expected_hash):
Uses a constant-time comparison algorithm to safely match signatures without exposing timing side-channels.