Authentication Basics — Passwords, Sessions & Tokens
Authentication vs authorization, storing passwords (Argon2id/bcrypt, salts, peppers), login flows and account security, server-side sessions vs stateless tokens, cookie security, JWT structure, signing algorithms and pitfalls, access and refresh tokens with rotation, and logout/revocation.
Who are you vs what may you do
| Authentication | Authorization | |
|---|---|---|
| Question | who are you? | are you allowed to do this? |
| Mechanisms | passwords, passkeys, OTP, SSO, certificates | roles, ownership, policies, scopes |
| When | login / each request's credential check | every request, every object |
| Failure | 401 Unauthorized | 403 Forbidden (or 404 to hide existence) |
Storing passwords
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher() # Argon2id with sensible defaults
def register(password: str) -> str:
return ph.hash(password) # store this string
def login(stored: str, attempt: str) -> bool:
try:
ph.verify(stored, attempt) # constant-time comparison inside
except VerifyMismatchError:
return False
if ph.check_needs_rehash(stored): # parameters upgraded since registration
save_new_hash(ph.hash(attempt))
return True
import argon2 from "argon2";
const hash = await argon2.hash(password, { type: argon2.argon2id });
const ok = await argon2.verify(hash, attempt);
Sessions (stateful)
Session rules:
- 128+ bits of randomness for the ID; regenerate it on login and privilege change (prevents session fixation).
- Cookie:
HttpOnly; Secure; SameSite=Lax; Path=/(use the__Host-prefix). - Idle timeout + absolute lifetime; server-side invalidation on logout.
- CSRF protection for state-changing requests (SameSite + CSRF tokens/origin checks) — see API security.
Tokens and JWTs (stateless)
Text
eyJhbGciOiJFUzI1NiIsImtpZCI6ImsxIn0 ← header {"alg":"ES256","kid":"k1"}
.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c3JfNDIiLCJhdWQiOiJhcGkiLCJleHAiOjE3OTEzOTE4MDAsInNjb3BlIjoib3JkZXJzOnJlYWQifQ
← payload {"iss":"https://auth.example.com","sub":"usr_42","aud":"api","exp":1791391800,"scope":"orders:read"}
.MEUCIQDf… ← signature over header.payload
Verifying a JWT correctly
import jwt # PyJWT
jwks = jwt.PyJWKClient("https://auth.example.com/.well-known/jwks.json")
def verify(token: str) -> dict:
key = jwks.get_signing_key_from_jwt(token)
return jwt.decode(
token, key.key,
algorithms=["ES256"], # pin! never trust the header's alg
audience="api", # this token must be meant for us
issuer="https://auth.example.com",
options={"require": ["exp", "iat", "sub"]},
leeway=30, # small clock-skew tolerance
)
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
export async function verify(token: string) {
const { payload } = await jwtVerify(token, JWKS, {
algorithms: ["ES256"],
audience: "api",
issuer: "https://auth.example.com",
});
return payload;
}
HS256 vs RS256/ES256
| HS256 (HMAC) | RS256 / ES256 / EdDSA | |
|---|---|---|
| Key | one shared secret | private key signs, public key verifies |
| Who can mint tokens | anyone who can verify | only the issuer |
| Fits | single service | many services / third parties (publish a JWKS) |
Sessions vs JWT
| Server-side session | JWT access token | |
|---|---|---|
| State | server (Redis/DB) | in the token |
| Per-request cost | one cache lookup | signature verification |
| Revocation | instant | hard until expiry (needs denylist/versioning) |
| Size | small cookie | hundreds of bytes – KBs |
| Cross-domain / multi-service | needs shared store | easy |
| Data freshness | always current | stale claims until expiry |
| Best for | first-party web apps | APIs, mobile, service-to-service, SSO |
Access + refresh tokens
Where to keep tokens on the client
| Client | Recommended storage |
|---|---|
| Browser SPA | best: BFF pattern (tokens stay server-side, browser gets a session cookie); else in memory + refresh via HttpOnly cookie. Avoid localStorage for long-lived tokens (XSS). |
| Mobile app | OS keychain/keystore |
| Server / CLI | secrets manager, env injected at runtime, file with strict permissions |
Account security essentials
- MFA (TOTP, WebAuthn/passkeys) — see Advanced authentication.
- Rate-limit login, signup, password reset and OTP verification.
- Generic error messages; constant-time comparisons; no user enumeration.
- Password reset tokens: random, single-use, short expiry, hashed at rest; invalidate sessions on reset.
- Email verification and change-of-email confirmation to the old address.
- Notify users of new logins and security changes; keep an audit trail.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.