SyntaxPilot
Courses/System Design/Lesson 26

System Design · Lesson 26 of 40 · 13 min

Security basics: auth, OAuth, JWT, encryption

queued

These are the notes for System Design episode 26. A stranger types "I'm Priya" into a request and ChaiNow's payment service happily pays from her wallet. You'll fix that step by step: ask for a password (authentication), discover that passwords stored as typed leak in one backup file, store a hash instead, watch two users with the same password get the same hash and a five-word list crack everyone, add a random salt and a slow hash (PBKDF2, 600,000 rounds), stop sending the password on every tap by handing out a signed token (a JWT), catch a forged "admin" token with ValueError: invalid signature, separate 401 Unauthorized from 403 Forbidden, let a third-party app in without your password using OAuth 2.0, and finally stop strangers on café Wi-Fi from reading it all with HTTPS/TLS and encryption at rest. Every demo is plain Python (standard library only) and runs as-is; outputs are real (Python 3.13). Salts, salted hashes, exp values and timings change on every run, so yours will differ. ChaiNow and ChaiStats are made up.

Security, for a system designer, means three promises: only the right people get in, they can only do what they're allowed to do, and nobody else can read or change the data on the way or on disk. Example: a stranger can't pay from Priya's wallet, Priya can't open the admin page, and the café Wi-Fi sees only scrambled bytes.

The problems

Problem What it teaches
Anyone can say "I'm Priya" Authentication: proof of identity, passwords
Passwords stored as typed leak Hashing: store a one-way fingerprint (SHA-256), not the password
Same password, same hash; fast guessing Salts, slow hashes (PBKDF2, bcrypt, scrypt, Argon2id), rainbow tables, OWASP's advice
Password on every tap? Signed tokens: JWT (header, payload, signature), HMAC, exp, 401 vs 403, authorization
Third-party apps want your password OAuth 2.0: roles, access tokens, scopes, revoking
Café Wi-Fi reads everything Encryption, HTTPS = HTTP inside TLS, certificates, encryption in transit and at rest

Problem 1: who are you? (authentication)

In episode 20 we moved the login check into the API gateway. But look at what a request to ChaiNow's payment service actually says:

{"user": "priya", "action": "pay", "amount": 450}

The payment service believes it. One night a stranger sends the same request: he simply typed her name. The server can't tell the difference, and Priya's wallet is empty.

A bank never pays just because you say your name. It asks for proof: your signature, your card, your PIN, something only you know or have. Checking who someone really is, is called authentication. Example: the ATM asks for your PIN before it shows your balance.

The simplest proof on the web is a password: a secret word that only the user knows. Example: Priya chose chai@123.

First try: store passwords as typed

users = {}                               # the user table in our database

def signup(name, password):
    users[name] = password               # store it exactly as typed

def login(name, password):
    return users.get(name) == password

signup("priya", "chai@123")
signup("rahul", "rahul2004")
signup("neha", "chai@123")
print("priya logs in:", login("priya", "chai@123"))

# one night, a backup file of the database leaks...
for name, pw in users.items():
    print("LEAKED:", name, "->", pw)

Output:

priya logs in: True
LEAKED: priya -> chai@123
LEAKED: rahul -> rahul2004
LEAKED: neha -> chai@123
  • users is a Python dictionary standing in for the database's user table: name → stored value.
  • users.get(name) returns None if the name doesn't exist, so an unknown user simply fails to log in.
  • Login works. But the leaked backup shows every password in plain text. Plain text means readable as-is, with no protection.
  • Worse, people reuse passwords. The attacker now tries chai@123 on Priya's email and her bank.

The key insight: the server never needed to know the password itself. It only needs to check that you know it. Store a check, not the password.

Problem 2: hashing (the fingerprint)

The police keep your fingerprint, not your hand. A fingerprint is small, it identifies you, and nobody can rebuild your hand from it.

Fingerprints Password hashes
Police keep your fingerprint, not your hand Store the hash: sha256("chai@123") = e0ac55b9...
Match a new print to it: same finger, same print At login: hash the typed password and compare. Same input, same hash
Can't rebuild a hand from a print One-way: you can't turn a hash back into the password

A hash function turns any input (a word, a file, a whole book) into a short, fixed-size value called a hash (also digest). Three properties matter here:

  1. Deterministic: the same input always gives the same hash.
  2. Fixed size: a tiny password and a long sentence both give a hash of the same length.
  3. One-way: easy to compute, practically impossible to undo. A tiny change in the input gives a completely different hash.

SHA-256 is a widely used hash function (part of the SHA-2 family). It outputs 256 bits = 32 bytes, usually shown as 64 hex characters (hex is base 16: digits 0-9 and a-f, two characters per byte).

import hashlib

for pw in ["chai@123", "chai@123", "chai@124", "a much, much longer password than the others"]:
    d = hashlib.sha256(pw.encode()).hexdigest()
    print(f"{pw[:20]:<20} {d[:16]}...  ({len(d)} hex chars)")

Output:

chai@123             e0ac55b93f0722e9...  (64 hex chars)
chai@123             e0ac55b93f0722e9...  (64 hex chars)
chai@124             f43da98e04c9ee72...  (64 hex chars)
a much, much longer  226ed4d604742379...  (64 hex chars)
  • pw.encode() turns the text into bytes (UTF-8); hash functions work on bytes, not text.
  • .hexdigest() gives the hash as 64 hex characters; we print the first 16.
  • Same input, same hash (lines 1 and 2). One character changed (3 → 4), totally different hash. Long input, same 64 characters.

Second try: store SHA-256 hashes

import hashlib, time

def h(pw):                               # one-way: easy to compute, can't undo
    return hashlib.sha256(pw.encode()).hexdigest()

users = {"priya": h("chai@123"), "rahul": h("rahul2004"), "neha": h("chai@123")}
for name, digest in users.items():
    print(name, digest[:16] + "...")

# the attacker hashes a list of common passwords once...
guesses = ["123456", "password", "chai@123", "qwerty", "rahul2004"]
table = {h(g): g for g in guesses}
for name, digest in users.items():
    print("cracked:", name, "->", table.get(digest))

start = time.perf_counter()
for i in range(1_000_000):
    h(str(i))
print(f"1,000,000 guesses in {time.perf_counter() - start:.1f} s")

Output (the last line's timing depends on your machine; the video's run showed 1.1 s):

priya e0ac55b93f0722e9...
rahul 590b94547c28dfe4...
neha e0ac55b93f0722e9...
cracked: priya -> chai@123
cracked: rahul -> rahul2004
cracked: neha -> chai@123
1,000,000 guesses in 0.7 s

What went wrong:

  • Priya and Neha have exactly the same hash. Same password, same fingerprint, so anyone who cracks one has cracked both, and the leak itself shows who shares a password.
  • The attacker can't undo a hash, so he does the opposite: he hashes a list of likely passwords once and builds a lookup table hash → password. Then every leaked hash is a single dictionary lookup. A five-word list cracked all three accounts. A big precomputed table of password hashes like this is the idea behind a rainbow table (a real rainbow table is a cleverer, compressed version of our table).
  • SHA-256 is fast: about a million guesses a second on one ordinary laptop core. Speed is great for checking files, terrible for passwords.
  • time.perf_counter() is a high-resolution clock for measuring how long code takes.

OWASP (the Open Worldwide Application Security Project, a community that publishes free web-security guidance) says it plainly in its Password Storage Cheat Sheet: "Fast hashing algorithms such as SHA-256 are not suitable for password storage", because they "allow attackers to perform large numbers of guesses quickly".

A fast hash means fast guessing.

Problem 3: salt and slow hashes (the masala blend)

A chai stall Password storage
Every stall uses the same recipe: taste one, know them all Plain hash: same password, same hash; one table cracks everyone
Each stall adds its own secret pinch of masala, written on the jar Salt: random bytes per user; same password, different hash
Brewing takes 5 minutes: you can't taste 1,000 recipes fast Slow hash: PBKDF2, bcrypt, Argon2id; every guess costs time

A salt, in OWASP's words, "is a unique, randomly generated string that is added to each password as part of the hashing process". Example: Priya's salt is 16 random bytes like 425ae0c0448107b2cc5a4d063c802771; Neha gets different ones. The salt is stored next to the hash. It is not secret: its job is only to make every hash unique. With a unique salt, OWASP says, "an attacker has to crack hashes one at a time", and salting "protects against ... rainbow tables" (a precomputed table can't include every possible salt).

A slow hash (a password hashing function) is a hash built to be deliberately expensive, usually by repeating work many times (iterations, also rounds or work factor), sometimes also by using a lot of memory. A real user logs in once and never notices a tenth of a second. An attacker who wants a million guesses pays that tenth of a second a million times.

PBKDF2 (Password-Based Key Derivation Function 2) is one such function: it repeats HMAC-SHA256 (a keyed version of SHA-256, explained in Problem 4) many times. OWASP's recommended count for PBKDF2-HMAC-SHA256 is 600,000 iterations. Python has it built in as hashlib.pbkdf2_hmac.

Third try: salted, slow hashes

import hashlib, hmac, os, time

def hash_password(pw):
    salt = os.urandom(16)                # random, different for every user
    digest = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 600_000)
    return salt, digest                  # store both

def check(pw, salt, digest):
    again = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 600_000)
    return hmac.compare_digest(again, digest)

users = {n: hash_password(p) for n, p in
         [("priya", "chai@123"), ("neha", "chai@123")]}
for name, (salt, digest) in users.items():
    print(name, digest.hex()[:16] + "...")

start = time.perf_counter()
print("priya logs in:", check("chai@123", *users["priya"]))
print(f"one guess takes {time.perf_counter() - start:.2f} s")
print("wrong password:", check("chai@124", *users["priya"]))

Output (one run; the salts are random, so the hashes differ on every run, and the timing depends on your machine; the video's run showed 0.10 s):

priya 3fb7120f8b050021...
neha cbde7017fc7b4f60...
priya logs in: True
one guess takes 0.12 s
wrong password: False

How it works:

  • os.urandom(16) returns 16 random bytes from the operating system's secure random source. Every signup gets a fresh salt.
  • hashlib.pbkdf2_hmac("sha256", password_bytes, salt, 600_000) runs HMAC-SHA256 600,000 times and returns a 32-byte digest. We store both the salt and the digest.
  • check repeats exactly the same work with the stored salt. Same password + same salt → same digest.
  • *users["priya"] unpacks the stored (salt, digest) pair into the last two arguments of check.
  • hmac.compare_digest(a, b) compares two values in constant time: it takes the same time whether the first byte or the last byte differs. A plain == can stop at the first different byte, and an attacker measuring response times very precisely could learn how many leading bytes were right. This kind of leak through timing is a timing attack.

What changed:

  • Same password, completely different hashes, because the salts differ. The attacker's table is useless; he must attack each user separately.
  • One check takes about 0.1 s. A million guesses at 0.1 s each is 100,000 s, about 27.8 hours, for just one user. Compare 0.7 s for a million unsalted SHA-256 guesses against everyone at once.

You just invented salted password hashing.

Which slow hash for real? (OWASP)

OWASP's Password Storage Cheat Sheet lists, in order of preference:

Choice Algorithm OWASP's minimum settings
1 Argon2id 19 MiB of memory, 2 iterations, parallelism 1
2 scrypt the fallback if Argon2id isn't available
3 bcrypt (legacy, older systems) work factor 10 or more; note its 72-byte password limit
4 PBKDF2-HMAC-SHA256 600,000 iterations
✗ plain text, or a fast hash like SHA-256 alone never
  • Argon2id is memory-hard: each guess needs a lot of memory (at least 19 MiB; a mebibyte is 1,048,576 bytes), so attackers can't cheaply run millions of guesses side by side. Parallelism is how many threads one hash uses.
  • bcrypt's 72-byte limit means anything after the 72nd byte of a password is ignored.
  • Your language's libraries already implement these. Never write your own password hashing (our demos are for learning).

Hash, don't encrypt

Why not encrypt passwords instead? Encryption scrambles data with a key so that only someone with the key can turn it back (decrypt). As OWASP puts it: "Since encryption is a two-way function, attackers can retrieve the original plaintext". Whoever steals the key gets every password back. A hash can't be undone at all, with or without a key.

Passwords: hash them (salted, slow). Don't encrypt them, and never store them as typed.

Problem 4: signed tokens (the cinema ticket)

Priya taps menu, cart, pay, track. Should the app send her password with every tap? Each check costs about 0.1 s of server work, and the password travels across the network again and again, each time a chance to be stolen.

A cinema solves this. You pay once at the counter and get a ticket. At the door you show the ticket, not your money. And the ticket carries the cinema's stamp, so the guard can spot a fake without phoning the counter.

Cinema Web app
Pay once at the counter Log in once with the password
A ticket: "Screen 3, Row F, 7 pm" A token with claims: "sub: priya, role: customer, exp: 15 min"
The cinema's stamp The signature
The guard checks the stamp at the door Each service verifies the signature, no database lookup
The ticket is for tonight only exp: the token expires

A token is a piece of data the server gives you after login that you send back with each request to prove you already logged in. A claim is one statement inside it, like "sub": "priya" (sub = subject, who the token is about) or "role": "customer".

The standard format is the JSON Web Token (JWT), defined in RFC 7519 (May 2015). (An RFC, "Request for Comments", is a numbered document that defines an internet standard.) RFC 7519 describes a JWT as "a compact, URL-safe means of representing claims to be transferred between two parties". It has three URL-safe parts separated by periods:

header.payload.signature
Part Contains Example (before encoding)
Header How the token is signed {"alg": "HS256", "typ": "JWT"} (RFC 7519's example is {"typ":"JWT","alg":"HS256"})
Payload The claims {"sub": "priya", "role": "customer", "exp": 1793653279}
Signature HMAC-SHA256 of header.payload with the server's secret 32 bytes
  • HS256 means HMAC with SHA-256.
  • exp (expiration time): RFC 7519 says it "identifies the expiration time on or after which the JWT MUST NOT be accepted for processing". It's a Unix timestamp: seconds since 1 January 1970 (UTC). int(time.time()) + 900 means "15 minutes from now".
  • Each part is written in base64url: a way to write any bytes using only letters, digits, - and _, safe to put in a URL. JWTs also drop the = padding at the end.

Base64 is an encoding: it only changes the format of data, and anyone can undo it, no key needed:

import base64
header = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9"
print(base64.urlsafe_b64decode(header + "=="))
print(base64.urlsafe_b64encode(b"chai@123"))
print(base64.urlsafe_b64decode(b"Y2hhaUAxMjM="))

Output:

b'{"alg": "HS256", "typ": "JWT"}'
b'Y2hhaUAxMjM='
b'chai@123'

That's why every JWT starts with eyJ: it's how {" looks in base64.

An HMAC (Hash-based Message Authentication Code) is a hash of a message mixed with a secret key. Example: hmac.new(SECRET, b"header.payload", hashlib.sha256). Anyone can compute SHA-256 of the message, but only someone with the secret can compute the right HMAC. So a valid HMAC proves the message was made by a key holder and hasn't been changed since. That is the cinema's stamp.

Building a JWT

import base64, hashlib, hmac, json, time
SECRET = b"only-chainow-servers-know-this"

def b64(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text): return base64.urlsafe_b64decode(text + "==")
def sign(msg):                            # HMAC-SHA256 with the secret
    return b64(hmac.new(SECRET, msg.encode(), hashlib.sha256).digest())

def make_token(claims):
    header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = header + "." + b64(json.dumps(claims).encode())
    return body + "." + sign(body)

def verify(token):
    header, payload, signature = token.split(".")
    if not hmac.compare_digest(sign(header + "." + payload), signature):
        raise ValueError("invalid signature")
    claims = json.loads(unb64(payload))
    if time.time() >= claims["exp"]:
        raise ValueError("token expired")
    return claims

token = make_token({"sub": "priya", "role": "customer",
                    "exp": int(time.time()) + 900})   # 15 minutes
print(token[:50] + "...")
print("verified:", verify(token))

Output (the exp number is "now + 900 seconds", so it changes every run):

eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiO...
verified: {'sub': 'priya', 'role': 'customer', 'exp': 1793653279}

How it works:

  • b64 encodes bytes as base64url and strips the = padding; unb64 adds == back (Python's decoder ignores extra padding, but fails with too little; see the mistakes table).
  • make_token builds header.payload and appends the signature of exactly that text.
  • verify splits the token into its three parts, recomputes the signature with the secret and compares (in constant time). Only if it matches does it trust the payload, and then it checks exp.
  • json.dumps turns a dictionary into JSON text; json.loads turns it back. (JSON is a text format for named fields, like {"sub": "priya"}.)
  • No database lookup: any service that has the secret can check a token in microseconds. That's why tokens like this are called stateless: the server doesn't need to remember anything about the session.

Attacking the JWT

import base64, hashlib, hmac, json, time
SECRET = b"only-chainow-servers-know-this"
def b64(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text): return base64.urlsafe_b64decode(text + "==")
def sign(msg):                            # HMAC-SHA256 with the secret
    return b64(hmac.new(SECRET, msg.encode(), hashlib.sha256).digest())

def make_token(claims):
    header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = header + "." + b64(json.dumps(claims).encode())
    return body + "." + sign(body)

def verify(token):
    header, payload, signature = token.split(".")
    if not hmac.compare_digest(sign(header + "." + payload), signature):
        raise ValueError("invalid signature")
    claims = json.loads(unb64(payload))
    if time.time() >= claims["exp"]:
        raise ValueError("token expired")
    return claims

token = make_token({"sub": "priya", "role": "customer",
                    "exp": int(time.time()) + 900})   # 15 minutes
print("verified:", verify(token))
h, p, s = token.split(".")                # anyone can READ the payload
print("payload:", unb64(p).decode())
fake = json.loads(unb64(p)); fake["role"] = "admin"
forged = h + "." + b64(json.dumps(fake).encode()) + "." + s
print("forged:", verify(forged))

Output (exp changes every run):

verified: {'sub': 'priya', 'role': 'customer', 'exp': 1793653279}
payload: {"sub": "priya", "role": "customer", "exp": 1793653279}
Traceback (most recent call last):
  File "forge.py", line 29, in <module>
    print("forged:", verify(forged))
                     ~~~~~~^^^^^^^^
  File "forge.py", line 16, in verify
    raise ValueError("invalid signature")
ValueError: invalid signature

Two lessons:

  1. Anyone can read a JWT. The payload printed in plain text, without the secret. A JWT is signed, not encrypted: never put a password, a card number or any secret inside.
  2. Nobody can change it. Priya changed customer to admin and kept the old signature. The signature was computed over the old payload, so it no longer matches, and verify refuses. To forge a valid signature you'd need the secret, which only ChaiNow's servers have. You just invented the JWT.

The flow, and 401 vs 403

login (password, once) → token (signed JWT) → each request (Authorization header) → verify (signature + exp)

The client sends the token with every request in the Authorization header (a header is a named piece of extra information sent with an HTTP request), commonly written Authorization: Bearer eyJ.... A bearer token is one where whoever holds ("bears") it is let in, like a cinema ticket: so it must not be stolen.

Now two different questions:

Question Name Example If the answer is no
Who are you? Authentication (authn) Is this token real and not expired? 401 Unauthorized: log in (again)
What may you do? Authorization (authz) Is Priya allowed to open the admin page? 403 Forbidden: logging in won't help

Authorization means deciding what a known user is allowed to do. Example: Priya is a real, logged-in customer, but only admins may open /admin. 401 and 403 are HTTP status codes (three-digit numbers the server sends back to say how a request went; 200 OK means success). Despite its name, 401 "Unauthorized" is really about authentication. MDN (Mozilla's web documentation) explains 403 Forbidden as "similar to 401, except that for 403 Forbidden responses, authenticating or re-authenticating makes no difference".

def status(token_ok, is_admin):
    if not token_ok:
        return "401 Unauthorized"         # who are you? log in
    if not is_admin:
        return "403 Forbidden"            # we know you; still no
    return "200 OK"

print("stranger, no token:", status(False, False))
print("priya, customer:  ", status(True, False))
print("asha, admin:      ", status(True, True))

Output:

stranger, no token: 401 Unauthorized
priya, customer:   403 Forbidden
asha, admin:       200 OK

Keep tokens short-lived. A stateless JWT can't be "un-issued": if someone steals it, it works until exp. A short exp (like our 15 minutes) limits the damage. Apps usually also give out a longer-lived refresh token, kept more carefully, that is used only to get a new short-lived token, so the user doesn't have to type the password every 15 minutes.

Problem 5: OAuth (the valet key)

An app called ChaiStats wants to show Priya her monthly chai spending. It asks for her ChaiNow password. That's like giving a hotel valet all your keys: car, house, locker.

RFC 6749 (October 2012), the OAuth 2.0 standard, lists what goes wrong when apps get your password:

  • the app stores your password;
  • it gets overly broad access: everything you can do, not just reading orders;
  • you can't revoke one app without changing your password (which breaks every other app too);
  • one compromised app exposes your password, and with it everything else.

Cars have a better idea: a valet key, which drives the car but can't open the boot, and which you can take back while your own keys keep working.

Hotel valet OAuth
Give the valet your house keys? Share your password: the app can do everything
A valet key: drives the car, can't open the boot An access token with a scope: "read orders only"
Take the valet key back; your keys still work Revoke one app's token; no password change

OAuth 2.0, in RFC 6749's words, "enables a third-party application to obtain limited access to an HTTP service". A third-party application is an app made by someone else (ChaiStats is not ChaiNow). RFC 6749 says "Access tokens are credentials used to access protected resources": an access token is the valet key. A scope is the list of permissions it carries. Example: orders:read (read orders) but not pay. To revoke a token is to cancel it so it stops working.

The four roles

Role (RFC 6749) Who it is in our story
Resource owner Priya, who owns the data
Client ChaiStats, the app that wants access
Authorization server ChaiNow's login server, which checks Priya and hands out tokens
Resource server ChaiNow's orders API, which holds the data and accepts tokens

The usual flow: "Log in with ChaiNow"

  1. ChaiStats sends Priya to ChaiNow's own login page.
  2. Priya logs in there, on ChaiNow, and approves one permission: "read my orders".
  3. ChaiNow sends Priya's browser back to ChaiStats with a short-lived one-time code (an authorization code).
  4. ChaiStats swaps the code, server to server, for an access token, and calls the orders API with it.

The app never sees the password. It gets a limited, revocable key instead. You just invented OAuth. The mini project below builds a tiny version of steps 2 to 4 (a grant with a scope, and revoking it).

Problem 6: HTTPS and encryption (the café Wi-Fi)

Priya orders from a café on free public Wi-Fi. Her phone sends the token with every request. Over plain HTTP, every byte is readable by anyone on the same network. A stranger copies Authorization: eyJ... and, for the next 15 minutes, he is Priya. Salts and signatures don't help if the token itself is stolen.

So we lock every message in a box that only the server can open. That's encryption: scrambling data with a key so that only the key holder can read it. The scrambled form is the ciphertext; the readable form is the plaintext.

A toy that shows the idea (two-way, needs the key):

# TOY ONLY: shows "two-way, needs the key". Never use XOR like this for real data;
# real systems use a well-tested encryption library.
import os

def xor(data, key): return bytes(b ^ k for b, k in zip(data, key))

secret = b"priya: 12 MG Road, Pune"       # what we want to store
key = os.urandom(len(secret))             # the key, kept somewhere else
locked = xor(secret, key)
print("on disk:     ", locked.hex()[:32] + "...")
print("with the key:", xor(locked, key))
print("no key, just guessing:", xor(locked, os.urandom(len(secret)))[:12], "...")

Output (one run; the key is random, so the bytes differ every run):

on disk:      a2d38c6821d718e8f29c43b3f4c02a27...
with the key: b'priya: 12 MG Road, Pune'
no key, just guessing: b'\x8e\xa0\xa1\x0e9t\xeb\x11\xf4\x9a\x95r' ...
  • ^ is XOR (exclusive or) on each byte. XOR-ing twice with the same key gives back the original, which is why the same function locks and unlocks.
  • With the key: the plaintext comes back. Without it: garbage. That's the difference from a hash (no way back at all) and from base64 (way back for anyone).

Encryption in transit: HTTPS and TLS

HTTPS is ordinary HTTP sent inside TLS (Transport Layer Security); it's the lock icon in your browser. Remember the TLS handshake from episode 1: before any HTTP is sent, the browser and server agree on keys, and from then on everything is encrypted. RFC 8446 (August 2018) defines TLS 1.3, which is "designed to prevent eavesdropping, tampering, and message forgery":

Threat Meaning Café example
Eavesdropping Reading data on the way The stranger reads Priya's token
Tampering Changing data on the way He changes "pay ₹450" to "pay ₹4,500"
Message forgery Sending fake messages that look real He pretends to be ChaiNow's server

How does Priya's phone know it's really talking to ChaiNow and not the stranger? A certificate: a digital document, signed by an organisation the phone already trusts (a certificate authority), that says "this public key belongs to chainow.in". (A public key is the half of a key pair you can share freely; only the server holds the matching private key.) If the stranger can't show a valid certificate for chainow.in, the connection is refused.

Python's ssl module shows what a careful HTTPS client checks by default (no network needed):

import ssl

ctx = ssl.create_default_context()      # what a careful HTTPS client uses
print("check certificate:", ctx.verify_mode.name)
print("check the name matches:", ctx.check_hostname)
print("TLS 1.3 available:", ssl.HAS_TLSv1_3)

Output (the last line depends on the OpenSSL library your Python was built with):

check certificate: CERT_REQUIRED
check the name matches: True
TLS 1.3 available: True
  • CERT_REQUIRED: the server must present a valid certificate, or the connection fails.
  • check_hostname: True: the certificate must be for the name you asked for (chainow.in), not just any valid certificate.
  • Protecting data while it moves across a network like this is encryption in transit.

Encryption at rest

Encryption at rest protects stored data: disks, database files, backups, especially sensitive fields like card data. If the leaked backup from Problem 1 had been encrypted (with the key kept somewhere else), the file alone would have been useless to the attacker. Encryption at rest and password hashing do different jobs: at rest protects the whole file if it's stolen; hashing protects passwords even from someone who can read the database.

Encode vs hash vs encrypt

Encode (base64) Hash (SHA-256, PBKDF2) Encrypt (TLS, disk encryption)
Purpose Change the format One-way fingerprint Keep it secret
Can it be undone? Yes, by anyone No Yes, but only with the key
Needs a key? No No (HMAC uses one to sign) Yes
In this episode JWT parts Password storage, JWT signature (HMAC) HTTPS, encrypted backups

The whole chain

  1. Anyone can type a name → ask for proof: a password (authentication).
  2. Plain passwords leak (LEAKED: priya -> chai@123) → store hashes.
  3. Same password, same hash; a million guesses in about a second → salt + slow hash (PBKDF2, 600,000 rounds, about 0.1 s per guess).
  4. Password on every tap → a signed JWT with exp; forgery gives ValueError: invalid signature; 401 = who are you, 403 = not allowed.
  5. Apps want your password → OAuth: a limited, revocable access token with a scope.
  6. Café Wi-Fi reads the token → HTTPS (TLS) for data in transit, encryption at rest for stored data.

Common mistakes (and the real outputs)

Mistake Code Output Fix
Fast, unsalted hash hashlib.sha256(pw.encode()).hexdigest() 1,000,000 guesses in 0.7 s; equal passwords have equal hashes Argon2id / scrypt / bcrypt / PBKDF2 with a random salt per user
Hashing text, not bytes hashlib.sha256("chai@123") TypeError: Strings must be encoded before hashing hashlib.sha256("chai@123".encode())
One salt for everybody SALT = b"chainow" Priya and Neha: 91611cdd1cb0d89b... both os.urandom(16) per user, stored with the hash
Decoding a JWT without verifying it json.loads(unb64(token.split(".")[1])) role: admin -> admin page opens! Always verify the signature and exp before trusting claims
Putting secrets in the payload {"sub": "priya", "password": ...} payload: {"sub": "priya", ...} readable by anyone Only non-secret claims; JWTs are signed, not encrypted
Forgetting base64url padding base64.urlsafe_b64decode("eyJzdWIiOiAicHJpeWEifQ") binascii.Error: Incorrect padding Add "==" back before decoding (as unb64 does)
Expired token used "exp": int(time.time()) - 60 ValueError: token expired Get a new token (refresh); keep exp short
401 for "not an admin" return 401 for a logged-in customer user logs in again... still blocked 403 Forbidden: identity is fine, permission isn't
Encrypting passwords encrypt(password, key) the key leaks → every password comes back Hash, don't encrypt
Sending tokens over plain HTTP http://chainow.in/... anyone on the Wi-Fi can copy Authorization: eyJ... HTTPS everywhere

The second mistake, run for real:

import hashlib
print(hashlib.sha256("chai@123").hexdigest())

Output:

Traceback (most recent call last):
  File "m1.py", line 2, in <module>
    print(hashlib.sha256("chai@123").hexdigest())
          ~~~~~~~~~~~~~~^^^^^^^^^^^^
TypeError: Strings must be encoded before hashing

The third mistake (a "salt" that is the same for everyone is no salt at all):

import hashlib
SALT = b"chainow"                        # one salt for everybody (wrong)
def h(pw):
    return hashlib.pbkdf2_hmac("sha256", pw.encode(), SALT, 600_000).hex()
print("priya", h("chai@123")[:16] + "...")
print("neha ", h("chai@123")[:16] + "...")

Output (identical on every run, which is exactly the problem):

priya 91611cdd1cb0d89b...
neha  91611cdd1cb0d89b...

It's slow, so each guess still costs time, but the attacker is back to one table for everyone, and the leak again shows who shares a password.

The fourth mistake (the signature only protects you if you check it):

import base64, json
def unb64(text): return base64.urlsafe_b64decode(text + "==")

def read_claims(token):                   # WRONG: decodes, never verifies
    return json.loads(unb64(token.split(".")[1]))

# a token the attacker typed by hand, with a junk signature
fake = ("eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9."
        + base64.urlsafe_b64encode(b'{"sub": "priya", "role": "admin"}')
          .rstrip(b"=").decode() + ".junk")
claims = read_claims(fake)
print("role:", claims["role"], "-> admin page opens!")

Output:

role: admin -> admin page opens!

The sixth mistake:

import base64
print(base64.urlsafe_b64decode("eyJzdWIiOiAicHJpeWEifQ"))

Output:

Traceback (most recent call last):
  File "m2.py", line 2, in <module>
    print(base64.urlsafe_b64decode("eyJzdWIiOiAicHJpeWEifQ"))
          ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/base64.py", line 134, in urlsafe_b64decode
    return b64decode(s)
  File "/usr/local/lib/python3.13/base64.py", line 88, in b64decode
    return binascii.a2b_base64(s, strict_mode=validate)
           ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
binascii.Error: Incorrect padding

Base64 text must be a multiple of 4 characters long; JWTs strip the = padding, so you add it back before decoding.

(File paths in the tracebacks are shortened to the file name.)

Mini project: a tiny login + token service

Everything from the episode in about 115 lines of plain Python: salted PBKDF2 password storage, login that returns a signed JWT, a tiny API that answers 200 / 401 / 403, an OAuth-style grant where Priya gives ChaiStats a token with only the orders:read scope, and revoking that token. Each token gets a random id (jti, "JWT ID") so it can be revoked individually.

# Mini project: ChaiNow's tiny login + token service (Python stdlib only)
import base64, hashlib, hmac, json, os, secrets, time

SECRET = secrets.token_bytes(32)          # signing key, made at startup
ROUNDS = 600_000                          # PBKDF2-HMAC-SHA256 (OWASP)
users = {}                                # name -> salt, hash, role
revoked = set()                           # token ids that were taken back

def b64(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text): return base64.urlsafe_b64decode(text + "==")
def sign(msg): return b64(hmac.new(SECRET, msg.encode(), hashlib.sha256).digest())

# ---- 1. passwords: salted, slow hash; never stored as typed
def signup(name, password, role="customer"):
    salt = os.urandom(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ROUNDS)
    users[name] = {"salt": salt, "hash": digest, "role": role}

def password_ok(name, password):
    u = users.get(name)
    if u is None:
        return False
    again = hashlib.pbkdf2_hmac("sha256", password.encode(), u["salt"], ROUNDS)
    return hmac.compare_digest(again, u["hash"])

# ---- 2. tokens: header.payload.signature (a JWT, HS256)
def make_token(claims):
    header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = header + "." + b64(json.dumps(claims).encode())
    return body + "." + sign(body)

def verify(token):
    parts = token.split(".")
    if len(parts) != 3:
        raise ValueError("malformed token")
    header, payload, signature = parts
    if not hmac.compare_digest(sign(header + "." + payload), signature):
        raise ValueError("invalid signature")
    claims = json.loads(unb64(payload))
    if time.time() >= claims["exp"]:
        raise ValueError("token expired")
    if claims["jti"] in revoked:
        raise ValueError("token revoked")
    return claims

def issue(sub, role, scope, client="chainow-app", minutes=15):
    return make_token({"sub": sub, "role": role, "client": client,
                       "scope": scope, "jti": secrets.token_hex(8),
                       "exp": int(time.time()) + minutes * 60})

def login(name, password):
    if not password_ok(name, password):
        return None                       # same answer for both mistakes
    return issue(name, users[name]["role"], ["orders:read", "pay"])

# ---- 3. OAuth-style grant: Priya approves ONE permission for an app
def grant(owner_token, client, scope):
    owner = verify(owner_token)           # she is logged in on ChaiNow
    return issue(owner["sub"], owner["role"], scope, client=client)

def revoke(token):
    revoked.add(verify(token)["jti"])

# ---- 4. the API: 401 = who are you? 403 = not allowed
ROUTES = {"GET /orders": {"scope": "orders:read"},
          "POST /pay":   {"scope": "pay"},
          "GET /admin":  {"role": "admin"}}

def handle(request, token):
    if token is None:
        return 401, "missing token"
    try:
        claims = verify(token)
    except ValueError as e:
        return 401, str(e)
    rule = ROUTES[request]
    if "role" in rule and claims["role"] != rule["role"]:
        return 403, f"{claims['sub']} is not {rule['role']}"
    if "scope" in rule and rule["scope"] not in claims["scope"]:
        return 403, f"{claims['client']} lacks scope {rule['scope']}"
    return 200, f"ok for {claims['sub']} via {claims['client']}"

# ---- 5. a day at ChaiNow
start = time.perf_counter()
signup("priya", "chai@123")
signup("neha", "chai@123")
signup("asha", "masala#chai#2026", role="admin")
print(f"3 signups in {time.perf_counter() - start:.2f} s")
print("same password, same hash?",
      users["priya"]["hash"] == users["neha"]["hash"])

print("wrong password ->", login("priya", "chai@124"))
print("unknown user   ->", login("ravi", "chai@123"))
priya = login("priya", "chai@123")
asha = login("asha", "masala#chai#2026")

h, p, s = priya.split(".")
fake = json.loads(unb64(p)); fake["role"] = "admin"
forged = h + "." + b64(json.dumps(fake).encode()) + "." + s
old = make_token({**json.loads(unb64(p)), "exp": int(time.time()) - 1})
stats = grant(priya, "chaistats", ["orders:read"])

tests = [("no token",           "GET /orders", None),
         ("priya",              "GET /orders", priya),
         ("priya",              "GET /admin",  priya),
         ("asha (admin)",       "GET /admin",  asha),
         ("forged admin token", "GET /admin",  forged),
         ("expired token",      "GET /orders", old),
         ("chaistats",          "GET /orders", stats),
         ("chaistats",          "POST /pay",   stats)]
for who, req, tok in tests:
    print(f"{who:<19} {req:<12} ->", *handle(req, tok))

revoke(stats)                             # Priya takes the valet key back
print("after revoke:")
print(f"{'chaistats':<19} {'GET /orders':<12} ->", *handle("GET /orders", stats))
print(f"{'priya':<19} {'POST /pay':<12} ->", *handle("POST /pay", priya))

Output (only the first line's timing changes between runs; the signing key, salts and tokens are random but never printed):

3 signups in 0.34 s
same password, same hash? False
wrong password -> None
unknown user   -> None
no token            GET /orders  -> 401 missing token
priya               GET /orders  -> 200 ok for priya via chainow-app
priya               GET /admin   -> 403 priya is not admin
asha (admin)        GET /admin   -> 200 ok for asha via chainow-app
forged admin token  GET /admin   -> 401 invalid signature
expired token       GET /orders  -> 401 token expired
chaistats           GET /orders  -> 200 ok for priya via chaistats
chaistats           POST /pay    -> 403 chaistats lacks scope pay
after revoke:
chaistats           GET /orders  -> 401 token revoked
priya               POST /pay    -> 200 ok for priya via chainow-app

What to notice:

  • Passwords are never stored. Priya and Neha share chai@123, but their stored hashes differ (False), thanks to per-user salts. Three signups cost about a third of a second: 0.1 s each, by design.
  • Login gives the same answer (None) for a wrong password and an unknown user, so an attacker can't use the login form to find out which names exist.
  • 401 vs 403: no token, a forged token and an expired token are all who are you? problems (401). Priya asking for /admin and ChaiStats trying to pay are you may not problems (403); logging in again wouldn't help either.
  • The forged admin token fails because its signature was made over the old payload.
  • Scopes limit the valet key: ChaiStats can read orders but not pay, even though the token is about Priya.
  • Revoking one app kills only ChaiStats' token; Priya's own token keeps working, and she never changed her password. The revoked set is one small piece of state the server must keep (and share between servers), which is the price of revoking stateless tokens before they expire.
  • secrets.token_bytes(32) and secrets.token_hex(8) give secure random bytes, like os.urandom. Because the key is made at startup, every token becomes invalid when the program restarts; a real service loads its key from a safe configuration store.

Extend it: in password_ok, still run PBKDF2 (with a dummy salt) when the user doesn't exist, so an unknown name takes as long as a wrong password (otherwise the time taken leaks which names exist); add a refresh function that swaps a long-lived refresh token for a new 15-minute access token; add a /orders rule that a token's sub may only read its own orders; reject tokens whose header alg isn't HS256.

Practice

  1. Homework: in the SALTED demo, try 100,000 rounds instead of 600,000. How long does one guess take?
  2. Homework: in the JWT demo, make exp already in the past. What error do you get?
  3. Homework: in the FORGE (or JWT) demo, change SECRET before calling verify. What happens, and why?
  4. Homework: which apps have you logged in to with another account (a "Log in with ..." button)? For one of them, name the four OAuth roles.
  5. One PBKDF2 check takes 0.1 s. How long do 1,000,000 guesses take against one user? Against 1,000 users with unique salts?
  6. 401 or 403? (a) no Authorization header; (b) a valid token for a customer calling DELETE /menu/42, which only admins may do; (c) a token whose exp passed 2 minutes ago; (d) a token whose payload was edited; (e) ChaiStats' orders:read token calling POST /pay.
  7. Decode this JWT payload by hand (in Python) and say who it's about: eyJzdWIiOiAibmVoYSIsICJyb2xlIjogImN1c3RvbWVyIiwgImV4cCI6IDE3OTM2NTMyNzl9.
  8. Encode, hash or encrypt? (a) storing passwords; (b) putting JSON in a URL; (c) a backup of the orders database; (d) the token on café Wi-Fi; (e) a JWT's signature.
  9. Why is the salt allowed to be stored right next to the hash, in the same table?
  10. A JWT is valid for 15 minutes and can't be revoked. A stolen token is used 3 minutes after it was issued. How long can the thief use it? What two things limit this?
Solutions and hints

1. Replace 600_000 with 100_000 in both places. One run:

priya a9987516f385ff2e...
neha ba02741ad856da05...
priya logs in: True
one guess takes 0.03 s
wrong password: False

The time is roughly proportional to the rounds: one-sixth of the rounds, about one-sixth of the time (0.12 s → 0.03 s here; your numbers will vary). Fewer rounds make life easier for attackers too, which is why OWASP gives a minimum.

2. Change the token line to "exp": int(time.time()) - 60}) # a minute ago:

eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiO...
Traceback (most recent call last):
  File "expired.py", line 26, in <module>
    print("verified:", verify(token))
                       ~~~~~~^^^^^^^
  File "expired.py", line 20, in verify
    raise ValueError("token expired")
ValueError: token expired

The signature is fine (the server made it), but time.time() >= claims["exp"], so RFC 7519's rule applies: it MUST NOT be accepted. A real API would answer 401, and the app would get a new token.

3. Add SECRET = b"a-different-secret" just before print("verified:", verify(token)) in the JWT demo:

eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiO...
Traceback (most recent call last):
  File "wrongkey.py", line 27, in <module>
    print("verified:", verify(token))
                       ~~~~~~^^^^^^^
  File "wrongkey.py", line 17, in verify
    raise ValueError("invalid signature")
ValueError: invalid signature

sign reads the global SECRET when it runs, so verify now computes a different HMAC. Even the real token is rejected: every service that checks tokens must share the same secret. It also shows why changing ("rotating") the secret logs everyone out.

4. Example: a news app with "Log in with ChaiNow". Resource owner: you. Client: the news app. Authorization server: ChaiNow's login server (the page where you typed your password). Resource server: ChaiNow's profile API that gives the app your name and email. The app received an access token, never your password.

5. 1,000,000 × 0.1 s = 100,000 s ≈ 27.8 hours for one user. With unique salts, each user is a separate attack: 1,000 users × 27.8 hours ≈ 27,800 hours (over 3 years) to try the same million guesses against everyone. Unsalted SHA-256: one table of a million hashes in about a second, then every user is a lookup.

6. (a) 401: no identity. (b) 403: we know who it is; logging in again won't help. (c) 401: expired, log in or refresh. (d) 401: invalid signature, we can't trust who it claims to be. (e) 403: the token is valid, but its scope doesn't allow paying.

7.

import base64
payload = "eyJzdWIiOiAibmVoYSIsICJyb2xlIjogImN1c3RvbWVyIiwgImV4cCI6IDE3OTM2NTMyNzl9"
print(base64.urlsafe_b64decode(payload + "==").decode())

Output:

{"sub": "neha", "role": "customer", "exp": 1793653279}

It's about Neha, a customer. No secret was needed, which is the point: a JWT payload is readable by anyone. Whether it's genuine is a separate question only the signature answers.

8. (a) hash (salted, slow); (b) encode (base64url); (c) encrypt (at rest); (d) encrypt (in transit, HTTPS/TLS); (e) hash, a keyed one (HMAC-SHA256).

9. The salt isn't a secret. Its only job is to make each user's hash unique, so a precomputed table (or one table for everyone) doesn't work and the attacker has to attack each hash one at a time. The check at login needs the salt, so it must be stored where the hash is.

10. Until exp: 15 − 3 = 12 more minutes. Limits: a short expiry (exp), and HTTPS, which makes stealing the token on the way much harder in the first place. (A revocation list, as in the mini project, is a third option, at the cost of the server keeping state.)

Quick quiz

# Two users chose the same password.
# In the leaked table, their stored values
# are IDENTICAL. What was missing?
  • A. Encryption
  • B. A salt
  • C. A JWT
  • D. HTTPS
Answer

B. A salt. A unique random salt per user makes the same password hash to different values, so one guess table can't crack everyone, and the attacker must attack each user separately. Encryption would make passwords recoverable with the key (worse); a JWT is for proving you already logged in; HTTPS protects data on the way, not in the stored table.

Interview questions

  • What's the difference between authentication and authorization? (Authentication: who are you? Proof of identity: password, token. Authorization: what may you do? Roles, scopes. Failures: 401 vs 403.)
  • How should a system store passwords? (Never as plain text or encrypted; hash each with a unique random salt using a slow password hashing function: Argon2id first, then scrypt, bcrypt for legacy, PBKDF2-HMAC-SHA256 with 600,000 iterations, per OWASP; compare in constant time.)
  • Why isn't SHA-256 good enough for passwords? (It's fast: about a million guesses a second on one core in our demo; OWASP says fast hashes "allow attackers to perform large numbers of guesses quickly". Unsalted, equal passwords also give equal hashes.)
  • What is a salt, and does it need to be secret? (Random bytes per user mixed in before hashing, stored with the hash; not secret; it makes hashes unique and defeats rainbow tables.)
  • What's inside a JWT, and how is it protected? (header.payload.signature, each base64url; the signature, e.g. HMAC-SHA256 with a server secret, detects any change; the payload is readable by anyone, so no secrets in it.)
  • How do you validate a JWT? (Split into three parts, recompute and compare the signature in constant time, then check exp and any other claims you rely on; only then trust the claims.)
  • Pros and cons of stateless tokens vs server-side sessions? (Tokens: any service can verify without a database lookup, scales easily; but they can't be revoked before exp without extra state, so keep them short-lived with refresh tokens, and maybe a revocation list.)
  • When do you return 401 and when 403? (401 when the request has no valid credentials: missing, forged or expired token. 403 when the user is known but not allowed; per MDN, re-authenticating makes no difference.)
  • What problem does OAuth 2.0 solve? (Third-party apps getting limited access without the user's password; RFC 6749 lists the problems of sharing passwords: stored by the app, overly broad access, no per-app revocation, one compromised app exposes the password.)
  • Name the OAuth 2.0 roles and walk through the usual flow. (Resource owner, client, authorization server, resource server; redirect to the authorization server's login, user approves scopes, one-time code back to the client, client swaps it server-to-server for an access token, calls the resource server.)
  • What does HTTPS protect against, and what doesn't it protect? (TLS protects data in transit from eavesdropping, tampering and message forgery, and certificates prove the server's identity; it doesn't protect data stored on disk (encryption at rest) or a server that's been broken into.)
  • Encoding vs hashing vs encryption? (Encoding: format change, reversible by anyone; hashing: one-way; encryption: reversible only with the key.)
  • How would you secure ChaiNow end to end? (HTTPS everywhere; salted slow password hashes; short-lived signed tokens verified at the gateway and services; roles/scopes checked per endpoint with correct 401/403; OAuth for third-party apps; encrypted disks and backups with keys stored separately.)

Glossary

Term Meaning
Security (system design) Only the right people get in, they do only what they're allowed, and nobody else can read or change the data
Authentication (authn) Checking who someone really is, e.g. a password or a valid token; failure → 401
Authorization (authz) Deciding what a known user may do, e.g. only admins open /admin; failure → 403
Credential Something that proves identity or access, e.g. a password or an access token
Password A secret word only the user knows, e.g. chai@123
PIN A short secret number, like the one an ATM asks for
Plain text Data stored or sent readable as-is, with no protection
Plaintext / ciphertext The readable data before encryption / the scrambled data after it
Password reuse Using the same password on several sites, so one leak opens them all
Hash function Turns any input into a fixed-size value; same input → same output; one-way
Hash / digest The output of a hash function, e.g. e0ac55b93f0722e9...
One-way Easy to compute, practically impossible to reverse
SHA-256 A widely used fast hash function: 256 bits = 32 bytes = 64 hex characters
Bit / byte A 0 or 1 / 8 bits
Hex Base 16 (0-9, a-f); two hex characters = one byte
.encode() Turns Python text into bytes (UTF-8), which hash functions need
Lookup table A precomputed hash → password dictionary, like table in the HASHED demo
Rainbow table A large precomputed (and compressed) table for reversing unsalted password hashes; salts defeat it
Brute force / guessing attack Trying many passwords one after another until one matches
OWASP Open Worldwide Application Security Project, a community publishing free security guidance (e.g. the Password Storage Cheat Sheet)
Salt Unique random bytes per user, mixed in before hashing and stored with the hash; not secret
Slow hash / password hashing function A hash made deliberately expensive so each guess costs time (and maybe memory)
Iterations / rounds / work factor How many times the work is repeated; more = slower guesses
PBKDF2 Password-Based Key Derivation Function 2: repeats HMAC many times; OWASP: 600,000 iterations with HMAC-SHA256
bcrypt An older (legacy) password hash; OWASP: work factor 10+; ignores bytes after the 72nd
scrypt A memory-hard password hash; OWASP's fallback if Argon2id isn't available
Argon2id OWASP's first choice: memory-hard; minimum 19 MiB memory, 2 iterations, parallelism 1
Memory-hard Each guess needs a lot of memory, so running many guesses in parallel is expensive
MiB Mebibyte: 1,048,576 bytes
Parallelism How many threads one hash calculation uses
os.urandom / secrets Python's sources of secure random bytes, for salts, keys and token ids
Constant-time comparison Comparing values in the same time wherever they differ: hmac.compare_digest
Timing attack Learning secrets by measuring how long the server takes to answer
Encryption Scrambling data with a key so only the key holder can read it; two-way
Decryption Turning ciphertext back into plaintext with the key
Key The secret value that encryption, decryption or HMAC uses
Encoding Changing data's format, reversible by anyone, no key, e.g. base64
Base64 / base64url Writing bytes as letters, digits and two symbols; base64url uses - and _ so it's safe in URLs
Padding (=) = characters base64 adds so the length is a multiple of 4; JWTs strip them
Token Data the server gives after login, sent with each request to prove you're logged in
Bearer token A token that lets in whoever holds it, sent as Authorization: Bearer ...
Authorization header The HTTP header that carries the token with each request
Header (HTTP) A named piece of extra information sent with a request or response
JWT JSON Web Token (RFC 7519): header.payload.signature, each part base64url
RFC Request for Comments: a numbered document defining an internet standard
JSON A text format for named fields, e.g. {"sub": "priya"}
JWT header The first part: how the token is signed, e.g. {"alg": "HS256", "typ": "JWT"}
Payload The middle part of a JWT: the claims; readable by anyone
Claim One statement in a token, e.g. "role": "customer"
sub Subject claim: who the token is about, e.g. "priya"
exp Expiration time claim (a Unix timestamp); on or after it the token MUST NOT be accepted
jti JWT ID claim: a unique id for one token, used in the mini project to revoke it
Unix timestamp Seconds since 1 January 1970 (UTC), e.g. int(time.time())
Signature Proof the header and payload were made by a key holder and not changed
HMAC Hash-based Message Authentication Code: a hash mixed with a secret key
HS256 / HMAC-SHA256 HMAC using SHA-256; the alg of our JWTs
Signed vs encrypted Signed: anyone can read, nobody can change; encrypted: nobody without the key can read
Stateless token A token the server can check without remembering anything about it
Session The period a user stays logged in
Refresh token A longer-lived token used only to get new short-lived access tokens
Revoke Cancel a token so it stops working before it expires
Revocation list The set of revoked token ids the server checks (revoked in the mini project)
Role A label for what kind of user someone is, e.g. customer or admin
HTTP status code A three-digit number in a response saying how the request went, e.g. 200 OK
200 OK Success
401 Unauthorized No valid credentials (missing, forged or expired token): log in
403 Forbidden Known user, not allowed; re-authenticating makes no difference (MDN)
MDN Mozilla Developer Network: Mozilla's web documentation
Third-party application An app made by someone else that wants access to your data, e.g. ChaiStats
OAuth 2.0 RFC 6749: lets a third-party app get limited access to an HTTP service without your password
Resource owner The user who owns the data (Priya)
Client (OAuth) The app asking for access (ChaiStats)
Authorization server The server that logs the user in and issues tokens (ChaiNow's login server)
Resource server The API holding the data that accepts access tokens (ChaiNow's orders API)
Access token The credential an app uses to access protected resources: the valet key
Scope The permissions a token carries, e.g. orders:read but not pay
Authorization code The short-lived one-time code the client swaps for an access token
HTTP The protocol browsers and apps use to talk to servers; plain HTTP is readable on the network
HTTPS HTTP sent inside TLS: encrypted, the lock icon
TLS Transport Layer Security: encrypts a connection; TLS 1.3 is RFC 8446
TLS handshake The start of a TLS connection where both sides agree on keys (episode 1)
Eavesdropping / tampering / message forgery Reading / changing / faking messages on the way; what TLS 1.3 is designed to prevent
Certificate A signed document proving a public key belongs to a domain, e.g. chainow.in
Certificate authority An organisation devices trust to sign certificates
Public key / private key A key pair: the public half can be shared; only the server holds the private half
CERT_REQUIRED / check_hostname Python ssl settings: require a valid certificate / require it to match the name
Encryption in transit Protecting data while it moves over a network (HTTPS)
Encryption at rest Protecting stored data: disks, databases, backups
Backup A copy of data kept in case the original is lost; a classic source of leaks
XOR (^) Exclusive or on bits; XOR-ing twice with the same key gives back the original (toy demo only)
ValueError Python's error for a bad value; our verify raises it for invalid or expired tokens
TypeError Python's error for the wrong type, e.g. hashing text instead of bytes
binascii.Error Python's error for bad base64, e.g. Incorrect padding

Summary

  • Authentication asks who are you?; authorization asks what may you do? A name in a request proves nothing.
  • Never store passwords as typed (one leaked backup shows them all), and never encrypt them (steal the key, get them all). Hash them.
  • A fast hash like SHA-256 lets attackers guess about a million a second, and equal passwords give equal hashes. Use a unique random salt per user and a slow password hash: Argon2id, scrypt, bcrypt, or PBKDF2-HMAC-SHA256 with 600,000 iterations (OWASP). Compare with hmac.compare_digest.
  • After login, hand out a short-lived signed token. A JWT is header.payload.signature; anyone can read it, nobody can change it without the secret (ValueError: invalid signature). Always verify the signature and exp.
  • 401 = missing or bad credentials, log in. 403 = known but not allowed; logging in again won't help.
  • OAuth 2.0 gives third-party apps a limited, revocable access token with a scope instead of your password; four roles: resource owner, client, authorization server, resource server.
  • HTTPS (HTTP inside TLS) encrypts data in transit and certificates prove the server's identity; encryption at rest protects disks and backups. Encode = format, hash = one-way, encrypt = needs the key.

Next episode: that finishes the building blocks. From now on we design whole systems with everything so far, starting with the classic interview question: design a URL shortener.

Sources: OWASP Password Storage Cheat Sheet (fast hashes like SHA-256 "not suitable for password storage"; salt definition; unique salts force cracking "one at a time" and protect against rainbow tables; Argon2id 19 MiB / 2 iterations / parallelism 1, scrypt fallback, bcrypt work factor 10+ and 72-byte limit, PBKDF2-HMAC-SHA256 600,000 iterations; "Since encryption is a two-way function, attackers can retrieve the original plaintext"); RFC 7519, JSON Web Token, May 2015 (definition, URL-safe parts separated by periods, example header, exp); RFC 6749, OAuth 2.0, October 2012 (definition, problems with sharing passwords, the four roles, access tokens); MDN, 403 Forbidden; RFC 8446, TLS 1.3, August 2018 ("designed to prevent eavesdropping, tampering, and message forgery").