Sub topic 5
Building signed, expiring confirmation tokens
This chapter assumes you know basic Python, how HTTP GET and POST differ, and what an HMAC is at a high level. You should also know the three subscriber states from the lifecycle chapter: pending, confirmed, and unsubscribed. Here you build the token that turns a pending subscriber into a confirmed one.
What the token must do
A confirmation link in an email proves that whoever clicked it can read that mailbox. The link has to identify the address, and nobody else may be able to forge it. You could store a random string per subscriber in the database and look it up later. That works, but it needs a table, cleanup jobs, and a read on every click.
A signed token avoids that. It carries its own claims, and the server checks a signature instead of looking anything up. This design needs four properties:
- Integrity: an attacker cannot change the email address in the token and keep a valid signature.
- Purpose binding: a token made for confirming cannot be replayed as an unsubscribe or preference-centre token.
- Expiry: a token stops working after a set time, for example 48 hours.
- Safe comparison: checking the signature must not leak information through timing.
The token format
The token has two parts joined by a dot: payload.signature. The payload is a JSON array of [purpose, email, expires], URL-safe base64 encoded. The signature is HMAC-SHA256 over the raw payload bytes, using a secret only your server knows.
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 emailTo try it, set the secret before starting Python. Generate a real one with python -c "import secrets; print(secrets.token_urlsafe(32))".
# Run with: TOKEN_SECRET=change-me-please python demo.py
from tokens import make_token, verify_token # the code above, saved as tokens.py
token = make_token("[email protected]", "confirm")
print(token)
print(verify_token(token, "confirm")) # [email protected]
print(verify_token(token, "unsubscribe")) # None: wrong purpose
print(verify_token(token + "x", "confirm")) # None: signature mismatchHow verification works, step by step
The order of checks matters. The function parses the token, recomputes the signature, and compares it. It reads the claims only after the signature matches. Then it checks purpose and expiry.
Why each choice is made
| Choice | Reason |
|---|---|
| HMAC-SHA256 with a server secret | Only your server can produce a valid signature. A plain hash of the payload could be recomputed by anyone. |
| `hmac.compare_digest` | A normal `==` can return faster when the first bytes differ. Over many requests, that timing difference can help an attacker guess a signature byte by byte. |
| Purpose inside the signed payload | The signature covers the purpose, so changing it invalidates the token. |
| Expiry inside the signed payload | The client cannot extend the lifetime without breaking the signature. |
| Compact JSON with `separators` | The payload bytes are deterministic. The verifier signs the exact bytes it received, so formatting differences cannot cause false rejections. |
| URL-safe base64 without padding | The token survives in a URL path or query string without percent-encoding. The `=` padding is restored on decode. |
Returning one error for every failure
verify_token returns None for a malformed token, a bad signature, the wrong purpose, and an expired token. This is deliberate. Detailed errors help an attacker probe your system, for example to learn that a signature was right but the token had expired.
The user still needs a useful message. The landing page can say "This link is invalid or has expired" and offer to send a new one. The resend flow is covered in a later chapter. If you need to tell the cases apart for your own debugging, log the reason server-side, and never log the full token. Anyone who reads the log could use it while it is still valid.
Three decisions you have to make
Normalize the email address
Normalize the address before signing, for example with email.strip().lower(). The same normalization must be used when you store subscribers and when you query them. Otherwise [email protected] in the token will not match [email protected] in the UPDATE, and the confirmation will silently change no rows.
Choose a lifetime
48 hours is a common default for confirmation. A shorter lifetime reduces the window in which a forwarded or leaked email can be abused. A longer one rescues people who read mail slowly. Unsubscribe links are different: they should work for a very long time, because a recipient may open an old message months later and a dead unsubscribe link is a compliance and reputation problem. Pass a long ttl_seconds for that purpose, or sign unsubscribe tokens without an expiry using a separate function.
Plan for secret rotation
If TOKEN_SECRET changes, every outstanding token becomes invalid at once. For a confirmation token with a 48-hour life, that is tolerable. For unsubscribe links in old emails it is not. A common fix is to add a key ID to the token and keep a small dictionary of active keys. Verification picks the key named in the token, and new tokens use the newest key. The simple version in this chapter has one key, so treat rotation as a known limit.
What a signed token does not do
A signed token is stateless, so the server cannot know whether it was already used. Two clicks on the same valid link both pass verification. This is acceptable only if the action that follows is idempotent, meaning that repeating it has no extra effect. The confirmation UPDATE in the spine's landing page code does this by including AND status = 'pending'. A second call matches zero rows and changes nothing, so confirmed_at keeps its original time.
A token also does not prove who clicked. It proves that someone had the link. This is why the next chapters separate the GET that shows a page from the POST that changes state: some systems open links in emails before the human does, and a token alone cannot tell them apart.
If you need strictly single-use tokens, store a hash of each token or a nonce and mark it used. That reintroduces the lookup table you avoided, so add it only if a real requirement demands it.
Common errors
- Comparing signatures with
==. This works in tests and leaks timing in production. Usehmac.compare_digest. - Leaving the purpose out of the signed data. A confirmation token could then act as an unsubscribe or preference token.
- Trusting claims before checking the signature. Parse the payload only after the signature matches.
- Letting a missing
TOKEN_SECRETfall back to a default. Theos.environ[...]lookup raisesKeyErrorat startup. That is the behavior you want, because the service refuses to run unsafely. - Putting extra personal data in the payload. The payload is encoded, not encrypted. Anyone holding the link can decode it and read the email address, so include nothing more sensitive than that.
- Putting tokens in logs or analytics. Query strings often end up in access logs and referrer headers. Keep tokens out of both.
Exercise
A teammate changes make_token so that the payload is just [email, expires], and the purpose is chosen by which URL path the link points to (/confirm/TOKEN or /unsubscribe/TOKEN). What attack does this allow, and how do you fix it?
Show answer
Both URL paths would accept any valid token, because the signature does not cover the purpose. A person could take the token from a confirmation email and use it on /unsubscribe/, or the reverse. Using a confirmation token on the unsubscribe path would remove the subscriber, and an attacker who obtains an unsubscribe token could use it to confirm or to reach preferences. The fix is to put the purpose inside the signed payload, as [purpose, email, expires], and have each endpoint pass its own expected purpose to verify_token so that mismatches return None.
Exercise
verify_token("abc.def", "confirm") is called with a string that is not a real token. Which line stops it, and why does the function return None instead of raising an exception?
Show answer
The signature check stops it. The decoded signature bytes will not equal the recomputed HMAC, so hmac.compare_digest returns False and the function returns None. If the string cannot be decoded at all, the base64 or JSON parsing raises ValueError or TypeError, which the try/except catches and converts to None. Returning None for every failure keeps the caller simple and reveals nothing about why the token was rejected.