Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 80 ยท Projects

Project: Secure Token Service

Build a small token service in Python: sign tokens with HMAC, verify claims and expiry, rotate keys with key IDs, block replays and cover it all with tests.

Almost every web application needs a way to say "this request comes from alice, and she may do this for the next 15 minutes". The usual answer is a signed token. In Sessions, Cookies and JWTs you saw what such a token looks like and how it fails. In this project you'll build a small token service yourself, step by step, and make it fail in the right ways.

The service uses only the Python standard library: hmac for signatures, hashlib, base64 and json. By the end it will issue and verify tokens in the familiar three-part JWT layout, check every claim that matters, rotate signing keys without logging anyone out, refuse a one-time token that is presented twice, and come with a test suite. Everything runs on fake data, with fixed clocks so that the output is repeatable.

This is a teaching project. In production, use a maintained library for tokens (and for the cryptography underneath it) and keep your signing keys in a secrets manager. Building one yourself is the best way to understand what such a library has to get right.

What we are building

A token has three Base64URL parts separated by dots: a header (algorithm and key ID), a payload of claims, and a signature over the first two parts. The server only trusts the token after the signature and every claim check pass.

flowchart TD
    T["Incoming token"] --> S{"Three parts<br/>and valid encoding?"}
    S -- no --> R1["Reject: malformed"]
    S -- yes --> A{"Header alg is<br/>exactly HS256?"}
    A -- no --> R2["Reject: algorithm"]
    A -- yes --> K{"Known key ID?"}
    K -- no --> R3["Reject: unknown key"]
    K -- yes --> M{"Signature matches<br/>(constant time)?"}
    M -- no --> R4["Reject: bad signature"]
    M -- yes --> C{"iss, aud, nbf, exp<br/>all valid?"}
    C -- no --> R5["Reject: claims"]
    C -- yes --> J{"Single-use token<br/>already seen?"}
    J -- yes --> R6["Reject: replay"]
    J -- no --> OK["Accept"]

The order matters: nothing in the payload is trusted until the signature has been checked.

Stage 1: sign and verify

First the core: encode, sign, and verify with strict rules. Two details deserve attention. The verifier accepts exactly one algorithm and ignores what an attacker might prefer, and every decoding step is wrapped so that garbage input becomes a clean rejection instead of a crash.

Python Stage 1: a signed token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the forged payload keeps the old signature and still fails: the signature covers the exact header and payload text, so any edit breaks it. And alg: none fails because the verifier never lets the token choose how it is checked. This is the habit to keep: the server decides the rules, the token only supplies data.

Stage 2: validate the claims

A valid signature only proves the issuer made the token. It does not prove the token is meant for this service, or that it is still alive. That is the job of claims:

  • iss (issuer) and aud (audience): who made it and who it is for. Without an audience check, a token issued for your mail service might be accepted by your payment API.
  • iat, nbf and exp: issued at, not before, expires. Tokens must be short-lived, so you also cap the lifetime the verifier will accept.
  • A small leeway of a few seconds absorbs clock differences between servers; it must stay small.
Python Stage 2: claim checks with a fixed clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The string-typed exp case is a real bug class: in loosely typed code, comparing "9999999999" with a number can either crash or succeed in surprising ways. Reject unexpected types instead of guessing.

Stage 3: key rotation

Signing keys must change over time: on a schedule, and immediately after a suspected leak (see Randomness, Key Management and Secrets). If you simply swap the key, every token already issued fails at once and every user is logged out. The fix is the key ID (kid) in the header and a key ring that holds several keys with different roles:

  • one active key, used to sign new tokens;
  • retired keys, which can still verify tokens until those tokens have expired;
  • removed keys, which are gone: tokens signed with them fail.
flowchart LR
    A["k1 active"] -->|"rotate"| B["k1 retired, k2 active"]
    B -->|"after max token lifetime"| C["k1 removed, k2 active"]

A key should stay retired for at least as long as the longest token it signed can live. After a leak, skip straight to removal.

Python Stage 3: a key ring with rotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two safety points sit in this code. The kid is only a lookup label: an attacker who writes kid: "../../etc/passwd" or a SQL fragment into the header gets "unknown key", because the ring is a plain dictionary and the value is never used to open a file or build a query. And the secret is chosen by the server from the ring, never taken from the token.

Stage 4: replay defense

A stolen token is valid until it expires, no matter how many times it is used. For ordinary access tokens that is the accepted trade-off, which is why lifetimes are short (and why you pair them with HTTPS and cookie flags). For actions that must happen once (a password reset link, an email confirmation, a "confirm this payment" token) it is not acceptable. These tokens carry a unique jti (token ID), and the server remembers every jti it has accepted until the token's exp passes.

Remembering forever would grow without bound, but you only need to remember until expiry: after that the token is rejected by the exp check anyway.

Python Stage 4: a replay guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real deployment several servers answer requests, so the "seen" set lives in a shared store with an atomic insert-if-absent (for example Redis SET key value NX EX seconds). If checking and marking were two separate steps, two simultaneous requests could both pass the check.

Stage 5: the whole service, with tests

Now everything comes together in one class. The structure of verify follows the flowchart at the top exactly. Below it, a small test suite proves each defense with an assertion. Security code without tests tends to lose its protections silently during refactors, so each rejection reason has its own test.

Python Stage 5: TokenService and its tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Ideas to extend it

  • Refresh tokens: keep access tokens at 5 to 15 minutes and add a longer-lived, revocable refresh token stored server-side.
  • Revocation: keep a small deny-list of jti values (or a per-user "tokens issued before" timestamp) so you can log someone out immediately.
  • Asymmetric keys: replace HMAC with a signature algorithm (see Public-Key Cryptography) so that other services can verify without being able to issue.
  • Audit logging: log every rejection reason (never the token itself) and feed it into the alerts from Spotting Attacks in Logs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the verifier accept only the algorithm it expects instead of reading it from the token header?

    The token is attacker-controlled input. If it decides how it is verified, a forged token can ask not to be verified at all. The server must fix the rules.
  2. 2. A token has a valid signature but its aud claim names a different service. What should happen?

    A valid signature proves who issued the token, not who it is meant for. Without an audience check, a token for one service could be replayed against another.
  3. 3. How do you rotate a signing key without logging every user out?

    The kid in the header selects the key. The new key signs new tokens while the retired key still verifies older ones, and it is removed once those tokens can no longer be alive.
  4. 4. How long must a replay guard remember a single-use token's ID?

    After expiry the token is rejected by the expiry check anyway, so the guard can forget it. Remembering longer only wastes memory.
  5. 5. Why should the replay check be an atomic insert-if-absent in a shared store?

    If checking and marking are separate steps, two parallel requests with the same token can both see it as unused. A single atomic operation closes that race.

Summary

  • A token service signs the header and payload, and verifies the signature (in constant time) before trusting anything inside.
  • The server fixes the algorithm and the key lookup; the token only supplies data and a key ID label.
  • Always validate iss, aud, exp, nbf and the types of time claims, cap the lifetime, and keep leeway small.
  • Key IDs allow rotation: one active key signs, retired keys only verify, removed keys fail.
  • Single-use tokens need a jti and a replay guard that remembers IDs until expiry, with an atomic check in shared storage.
  • Give every rejection reason a test, so refactors cannot quietly remove a defense.

Next: Project: Phishing Email Classifier, where you'll train a small machine-learning model to flag suspicious messages.