python / expert
Snippet
Constant-Time HMAC Token Verification in Custom Auth Backends
Custom Django authentication backends should utilize hmac.compare_digest to mitigate side-channel timing attacks during cryptographic token signature validation.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import hmacimport hashlibfrom django.contrib.auth.backends import BaseBackendfrom django.contrib.auth.models import Userclass ConstantTimeHMACBackend(BaseBackend):def authenticate(self, request, token=None, signature=None, secret_key=None):if not (token and signature and secret_key):return Noneexpected_sig = hmac.new(secret_key.encode(), token.encode(), hashlib.sha256).hexdigest()if hmac.compare_digest(expected_sig, signature):return User.objects.filter(username=token).first()return None
django
Breakdown
1
class ConstantTimeHMACBackend(BaseBackend):
Subclasses Django BaseBackend to construct custom authentication pipelines.
2
expected_sig = hmac.new(secret_key.encode(), token.encode(), hashlib.sha256).hexdigest()
Computes SHA-256 HMAC signature using secret key and request token payload.
3
if hmac.compare_digest(expected_sig, signature):
Performs constant-time string comparison to neutralize timing side-channel exploits.