Sessions & Tokens (JWT)
HTTP is stateless: every request stands alone. After a user logs in, the server needs a way to recognise their later requests. There are two main approaches: server-side sessions and self-contained tokens such as JWTs.
| Server-side session | Self-contained token (JWT) | |
|---|---|---|
| What the client holds | A random session ID in a cookie | A signed token containing the claims |
| Where state lives | Server (memory, database, Redis) | Inside the token |
| Logout / revoke | Delete the session: immediate | Hard: the token stays valid until it expires (needs a deny-list) |
| Typical use | Classic web apps | APIs, single sign-on, service-to-service |
Both are fine when done right. The rules for sessions: generate IDs with a cryptographically secure random generator (secrets.token_urlsafe(32)), regenerate the ID at login (prevents session fixation), expire idle sessions, and send the cookie with Secure; HttpOnly; SameSite=Lax.
Session store model
import secrets
class SessionStore:
def __init__(self, idle_timeout=900):
self.sessions = {}
self.idle_timeout = idle_timeout
def create(self, user, now):
sid = secrets.token_urlsafe(32) # 256 bits of randomness
self.sessions[sid] = {"user": user, "last_seen": now}
return sid
def lookup(self, sid, now):
s = self.sessions.get(sid)
if s is None:
return None
if now - s["last_seen"] > self.idle_timeout:
del self.sessions[sid] # expired: remove it
return None
s["last_seen"] = now
return s["user"]
def destroy(self, sid):
self.sessions.pop(sid, None)
store = SessionStore()
sid = store.create("alice", now=1000)
print("id length:", len(sid))
print("valid id: ", store.lookup(sid, now=1500))
print("guessed id: ", store.lookup("guessed-id", now=1500))
print("after idle: ", store.lookup(sid, now=3000)) # idle for 1500 s
sid2 = store.create("alice", now=4000)
store.destroy(sid2) # logout
print("after logout:", store.lookup(sid2, now=4001))id length: 43
valid id: alice
guessed id: None
after idle: None
after logout: None
Anatomy of a JWT
A JSON Web Token has three Base64url-encoded parts separated by dots: header.payload.signature.
- Header: the algorithm, e.g.
{"alg": "HS256", "typ": "JWT"}. - Payload: the claims, such as
sub(subject/user),exp(expiry time),iat(issued at),iss(issuer),aud(audience). - Signature: for HS256, an HMAC-SHA256 over
header.payloadwith a secret key.
The payload is encoded, not encrypted. Anyone can read it, so never put secrets in a JWT.
Building and verifying an HS256 JWT
Real applications should use a maintained library (PyJWT, jose). Writing one from scratch, though, shows exactly what a verifier must check:
import base64
import hashlib
import hmac
import json
SECRET = b"demo-jwt-secret-use-32-secret-bytes" # DEMO ONLY
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def b64url_decode(text: str) -> bytes:
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def sign_jwt(claims: dict) -> str:
header = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
payload = b64url(json.dumps(claims, separators=(",", ":")).encode())
sig = hmac.new(SECRET, f"{header}.{payload}".encode(), hashlib.sha256).digest()
return f"{header}.{payload}.{b64url(sig)}"
token = sign_jwt({"sub": "alice", "role": "user", "exp": 1767229200})
print(token)
header, payload, sig = token.split(".")
print(json.loads(b64url_decode(payload))) # anyone can read the claimseyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzY3MjI5MjAwfQ.EO4PYZuRh7bn1nSItClkNtw68gPBAZ5qIIkS4eJCWzk
{'sub': 'alice', 'role': 'user', 'exp': 1767229200}
Now the verifier. It must check the algorithm is the one it expects (never trust the token's own alg to pick it), verify the signature in constant time, and check expiry and other claims, all before using anything in the payload:
import base64
import hashlib
import hmac
import json
SECRET = b"demo-jwt-secret-use-32-secret-bytes" # DEMO ONLY
def b64url(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def b64url_decode(text): return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def sign_jwt(claims, header=None):
h = b64url(json.dumps(header or {"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
p = b64url(json.dumps(claims, separators=(",", ":")).encode())
s = hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest()
return f"{h}.{p}.{b64url(s)}"
def verify_jwt(token, now):
try:
h, p, s = token.split(".")
header = json.loads(b64url_decode(h))
claims = json.loads(b64url_decode(p))
except ValueError:
return "invalid: malformed"
if header.get("alg") != "HS256":
return f"invalid: unexpected alg {header.get('alg')!r}"
expected = hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest()
if not hmac.compare_digest(expected, b64url_decode(s)):
return "invalid: bad signature"
if now >= claims.get("exp", 0):
return "invalid: expired"
return f"valid for {claims['sub']} ({claims['role']})"
now = 1767225600 # fixed "current time" for the demo
good = sign_jwt({"sub": "alice", "role": "user", "exp": now + 3600})
# 1. tamper with the payload: change role to admin, keep the old signature
h, p, s = good.split(".")
forged_payload = b64url(json.dumps({"sub": "alice", "role": "admin", "exp": now + 3600},
separators=(",", ":")).encode())
tampered = f"{h}.{forged_payload}.{s}"
# 2. the classic "alg: none" trick: no signature at all
none_header = b64url(b'{"alg":"none","typ":"JWT"}')
unsigned = f"{none_header}.{forged_payload}."
# 3. a token that has expired
expired = sign_jwt({"sub": "alice", "role": "user", "exp": now - 1})
for label, tok in [("genuine", good), ("tampered", tampered),
("alg none", unsigned), ("expired", expired), ("garbage", "abc")]:
print(f"{label:<9} {verify_jwt(tok, now)}")genuine valid for alice (user)
tampered invalid: bad signature
alg none invalid: unexpected alg 'none'
expired invalid: expired
garbage invalid: malformed
Every one of these checks corresponds to a real-world vulnerability: libraries that accepted alg: none, servers that decoded the payload without verifying, and tokens without expiry that stayed valid forever.
JWT best practices
- Pin the expected algorithm(s) in the verifier; reject everything else.
- Use a long random secret for HS256 (32+ bytes), or asymmetric algorithms (
RS256,EdDSA) when many services verify but only one issues. - Keep lifetimes short (minutes) and use refresh tokens that can be revoked server-side.
- Validate
exp,nbf,issandaud, so a token for one service can't be replayed against another. - In browsers, prefer an
HttpOnlycookie overlocalStorage: JavaScript (including injected XSS code) can readlocalStorage.
Go further: JWT Pitfalls breaks a naive verifier four ways (alg none, HS/RS confusion, exp and aud), and Session Fixation covers server-side sessions.
Test yourself
Is the payload of a signed JWT (HS256) secret?
- Yes, it's encrypted with the key
- No, it is only Base64url-encoded and anyone can read it
- Only the
subclaim is hidden - Only over HTTPS
A verifier reads alg from the token header and uses whatever algorithm it says. Why is this dangerous?
- It's slower
- An attacker can pick
noneor another weak option and bypass signature checks - JWT headers can't contain alg
- It breaks expiry checks
Why should the session ID be regenerated when a user logs in?
- To make cookies smaller
- To prevent session fixation, where an attacker plants a known ID before login
- Because IDs expire every minute
- To log the user out