{}DSA Atlas

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.

Intermediate7 interview questions

Who are you vs what may you do

AuthenticationAuthorization
Questionwho are you?are you allowed to do this?
Mechanismspasswords, passkeys, OTP, SSO, certificatesroles, ownership, policies, scopes
Whenlogin / each request's credential checkevery request, every object
Failure401 Unauthorized403 Forbidden (or 404 to hide existence)

Storing passwords

"hunter2" random salt Argon2idslow + memory-hard $argon2id$v=19$m=65536,t=3,p=4$salt$hash the stored string contains algorithm, parameters, salt and hash — upgrade parameters on next login
Store only a slow, salted hash; verify by re-hashing the login attempt.
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)

Browser Server Redis POST /login (email, password) SET sess:8f1c → {user: 42} EX 86400 Set-Cookie: sid=8f1c; HttpOnly; Secure; SameSite=Lax GET /orders (Cookie: sid=8f1c) GET sess:8f1c 200 (user 42's orders)
The cookie holds only a random ID; the state lives server-side, so revocation is instant.

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
Keyone shared secretprivate key signs, public key verifies
Who can mint tokensanyone who can verifyonly the issuer
Fitssingle servicemany services / third parties (publish a JWKS)

Sessions vs JWT

Server-side sessionJWT access token
Stateserver (Redis/DB)in the token
Per-request costone cache lookupsignature verification
Revocationinstanthard until expiry (needs denylist/versioning)
Sizesmall cookiehundreds of bytes – KBs
Cross-domain / multi-serviceneeds shared storeeasy
Data freshnessalways currentstale claims until expiry
Best forfirst-party web appsAPIs, mobile, service-to-service, SSO

Access + refresh tokens

Client Auth server API access (10 min) + refresh RT1 API calls with access token 401 token expired POST /token grant_type=refresh_token RT1 new access + RT2 (RT1 now invalid) if RT1 is ever presented again → theft detected → revoke the whole family
Short-lived access tokens limit exposure; rotating refresh tokens detect replay.

Where to keep tokens on the client

ClientRecommended storage
Browser SPAbest: 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 appOS keychain/keystore
Server / CLIsecrets 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

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.