python / intermediate
Snippet
Signed Timed Tokens for One-Time Django Action URLs
Django's TimestampSigner allows securely signing arbitrary data with an embedded timestamp. This is useful for time-sensitive, tamper-proof URLs such as password resets or single-use verification links without persisting state in the database.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.core.signing import TimestampSigner, SignatureExpired, BadSignaturesigner = TimestampSigner()def generate_action_token(user_id: int) -> str:return signer.sign(f"action-confirm:{user_id}")def verify_action_token(token: str, max_age_seconds: int = 3600) -> int | None:try:unsigned_value = signer.unsign(token, max_age=max_age_seconds)prefix, user_id_str = unsigned_value.split(":")return int(user_id_str)except (SignatureExpired, BadSignature):return None
django
Breakdown
1
from django.core.signing import TimestampSigner, SignatureExpired, BadSignature
Imports Django's cryptographic signing tools and exception classes for signature validation.
2
signer = TimestampSigner()
Instantiates a cryptographic signer that appends a timestamp to signed values.
3
return signer.sign(f"action-confirm:{user_id}")
Generates a signed, URL-safe string containing the payload and timestamp digest.
4
unsigned_value = signer.unsign(token, max_age=max_age_seconds)
Verifies authenticity and checks if the token age is within max_age_seconds.
5
except (SignatureExpired, BadSignature):
Catches invalid signatures or expired timestamps and safely returns None.