Authentication Tokens: Unique Doesn't Mean Unpredictable
Backend Basics: Authentication Tokens
Part 1 of 6 · Unique vs. unpredictable
You log in to an app, then open your account page. How does the backend know it’s still you?
One approach is to give your browser a token: a secret pass it sends with later requests. The backend checks whether that pass belongs to a valid session.
This series follows an authentication token from generation to verification, using Python examples. Let’s start with a question: why can’t we just give everyone a different number?
Different, but easy to guess
Try this in Python:
for number in range(1001, 1003):
print(f"session_{number}")
The loop uses 1001 and 1002, stopping before 1003. It prints:
session_1001
session_1002
No duplicates. But you can probably guess what comes next.
If that second token belongs to someone else, this is a problem. A token that grants access to whoever holds it is called a bearer token.
Unique means values don’t repeat. Unpredictable means seeing one doesn’t make the next practical to guess.
An email address might identify you, but someone else can know it. A timestamp comes from a clock, so knowing roughly when you logged in narrows the guesses. Neither makes a good secret pass.
What should we use instead?
We need enough secure randomness that even someone who knows the generation code can’t practically predict its next output.
Python provides secrets for security-sensitive values like authentication tokens. We’ll use it to build the random part in the next post.
Common misconception: “Hard to guess means safe”
Someone who copies your token from an exposed log doesn’t need to guess anything. Randomness helps prevent guessing; it doesn’t prevent theft. OWASP’s session guidance covers both risks.
Takeaway: Giving every session a different token isn’t enough. The token also needs to be hard to guess.
If someone saw your last three tokens, could they work out the fourth?
Next: Part 2 — Build a random authentication token in Python. We’ll read the expression one step at a time. After that: why secrets, how hard guessing is, what checksums do, and how the backend verifies a token.