Sub topic 5
Building signed, expiring confirmation tokens
This chapter assumes you know basic Python, how HTTP GET and POST differ, and that a database row can hold a subscriber's status. You will build the token that goes into the confirmation link and learn how to verify it safely.
Why a token is needed
A confirmation link must prove that whoever clicks it controls the mailbox. The link therefore carries a token that only your server can create. Without that protection, anyone could guess a link for another person's address and confirm it for them.
You have two common options:
| Approach | How it works | Trade-off |
|---|---|---|
| Random token in a database | Store a random value per sign-up and look it up on click | Needs a table and cleanup, easy to revoke |
| Signed token | Put the data in the token and sign it with a secret | No lookup to verify, hard to revoke before expiry |
This chapter uses a signed token. A signed token is a string that contains its own data plus a signature. The signature is a value computed from the data and a secret key. If anyone changes the data, the signature no longer matches.
What goes in the token
The token carries three values:
- Purpose: what the token may be used for, such as
confirm. This stops a confirmation token from working as an unsubscribe or preference token. - Email address: who the token is for.
- Expiry: a Unix timestamp after which the token is rejected.
The implementation
HMAC is a way to sign data using a shared secret. The code below uses HMAC with SHA-256. Set TOKEN_SECRET in the environment to a long random value, and never put it in source code.
import base64
import hashlib
import hmac
import json
import os
import time
SECRET = os.environ["TOKEN_SECRET"].encode()
def _b64e(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def _b64d(text: str) -> bytes:
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def make_token(email: str, purpose: str, ttl_seconds: int = 48 * 3600) -> str:
expires = int(time.time()) + ttl_seconds
payload = json.dumps([purpose, email, expires], separators=(",", ":")).encode()
signature = hmac.new(SECRET, payload, hashlib.sha256).digest()
return _b64e(payload) + "." + _b64e(signature)
def verify_token(token: str, purpose: str):
"""Return the email if the token is valid for this purpose, otherwise None."""
try:
payload_part, signature_part = token.split(".")
payload = _b64d(payload_part)
signature = _b64d(signature_part)
expected = hmac.new(SECRET, payload, hashlib.sha256).digest()
if not hmac.compare_digest(signature, expected):
return None
token_purpose, email, expires = json.loads(payload)
except (ValueError, TypeError):
return None
if token_purpose != purpose or expires < time.time():
return None
return emailSome points about this code:
- The payload is a JSON list, and the signature covers all of it. Changing the email, purpose, or expiry breaks the signature.
- Base64 URL encoding keeps the token safe to put in a link. The padding
=characters are removed and restored. hmac.compare_digestcompares in constant time. A plain==can leak, through timing differences, how many leading bytes matched.- The signature is checked before the payload is parsed. Unsigned input never reaches
json.loads. - Every failure returns
None, so the caller cannot tell a forged token from an expired one. The landing page can show one message for both.
Common errors
- Reusing one purpose everywhere. If confirmation and unsubscribe tokens share a purpose, a leaked confirmation link could unsubscribe someone. Always check the purpose.
- Comparing signatures with
==. Usehmac.compare_digest. - Long expiry for sensitive actions. 48 hours suits confirmation. Preference links might live longer, but keep them finite.
- Treating a valid token as proof of state. A token only proves the link was issued by you. The database row still decides whether the subscriber is pending or already confirmed.
- Rotating the secret carelessly. Changing
TOKEN_SECRETinvalidates every outstanding link. Plan for this, or accept that people will need a resend.
Exercise
A subscriber receives a confirmation token, then edits the email address inside the token to a different address and clicks the link. Why does verification fail, and which function call catches it?
Show answer
The signature was computed over the original payload. After the edit, the recomputed HMAC no longer matches the one in the token, so hmac.compare_digest(signature, expected) returns False and verify_token returns None. The attacker cannot produce a valid signature without knowing TOKEN_SECRET.
Exercise
Why does verify_token take a purpose argument instead of just returning whatever purpose is stored in the token?
Show answer
The caller states what it expects, and the function rejects any token made for another purpose. This stops a token issued for one action, such as confirmation, from being accepted for another, such as unsubscribe or preference changes.