Every system that stores anything worth having must answer two questions on every request: who is calling (authentication) and what are they allowed to do (authorization). This lesson covers the building blocks behind those answers: sessions and JWTs, OAuth 2.0 and OpenID Connect, password hashing, MFA and passkeys, access-control models, service-to-service identity and secrets. It closes with the attacks that break real systems most often, framed by the OWASP Top 10, and the defenses that stop them.
Think of it like
A hotel
At check-in the front desk verifies your passport (authentication) and hands you a key card. The card does not carry your name; it opens your room, the gym and the pool until checkout (a scoped, expiring token). Housekeeping has a card that opens every room on one floor (a role), and the manager can cancel any card instantly at the desk (revocation). If you lose the card, a thief gets into your room but cannot change the reservation, because that still requires the passport.
Authentication vs authorization
Authentication (AuthN)
- Proves identity: "this request comes from user 8812"
- Passwords, passkeys, one-time codes, client certificates, signed tokens
- Failure is
401 Unauthorized(despite the name, it means unauthenticated) - Happens once per login, then is carried by a session or token
Authorization (AuthZ)
- Decides access: "may user 8812 delete photo 42?"
- Roles, attributes, ownership, relationships, scopes
- Failure is
403 Forbidden(or404to avoid revealing that the resource exists) - Happens on every request, for every resource touched
Most serious breaches are authorization bugs, not broken cryptography: an endpoint that checks that you are logged in but not whether the order you asked for is yours. Keep that in mind through the rest of this lesson.
Sessions vs tokens
After login, the server must recognize the user on later requests without asking for the password again. There are two basic designs: keep the state on the server and give the client an opaque handle (sessions), or put the state in a signed token the client carries (self-contained tokens, usually JWTs).
Server-side sessions (stateful)
- Client holds a random session ID in a cookie; the server looks it up in Redis or a database
- Revocation is instant: delete the session row
- Every request needs a lookup (a fast cache hit, but a shared dependency)
- Simple, mature and the right default for a classic web app
Self-contained tokens (stateless)
- Client holds a signed token with claims (user, scopes, expiry); any service can verify it with a public key
- No lookup per request, which suits many services and third-party APIs
- Revocation is hard: a valid token stays valid until it expires
- Larger than an ID, and easy to misuse (long lifetimes, sensitive data in the payload)
Header {"alg":"ES256","typ":"JWT","kid":"2026-11"}
Payload {"iss":"https://auth.example.com","sub":"user_8812","aud":"photos-api",
"scope":"photos.read","iat":1793000000,"exp":1793000900,"jti":"b7f3c1"}
Signature ECDSA P-256 over base64url(header) + "." + base64url(payload)
Token = base64url(header) . base64url(payload) . base64url(signature)- iss (issuer)
- Who minted the token. Verifiers must accept only issuers they trust.
- sub (subject)
- Who the token is about, usually a stable user or client ID.
- aud (audience)
- Which service the token is for. An API must reject tokens minted for a different audience, or a token for one service could be replayed against another.
- exp, iat, nbf
- Expiry, issued-at and not-before times in Unix seconds. Keep access tokens short-lived (minutes).
- kid (key ID)
- Header hint telling the verifier which key from the issuer's published key set (JWKS) to use, which makes key rotation painless.
Refresh tokens and revocation
The standard compromise pairs a short-lived access token (5 to 15 minutes, verified statelessly) with a long-lived refresh token (days or weeks, stored and checked by the authorization server). Revoking a user means revoking the refresh token: their access token dies within minutes and cannot be renewed. With rotation, every refresh returns a new refresh token and invalidates the old one; if an old one is ever presented again, someone copied it, so the server revokes the whole token family and forces a fresh login.
| Access token | Refresh token | |
|---|---|---|
| Sent to | Every API call (Authorization: Bearer ...) | Only the authorization server's token endpoint |
| Lifetime | Minutes | Days to weeks, often with an absolute maximum |
| Verified by | Signature check, no lookup | Database lookup by the issuer |
| Revocation | Wait for expiry, or keep a small deny-list of jti values | Delete the row; immediate |
| If stolen | Usable until expiry | Rotation detects reuse and kills the whole token family |
Where the browser should keep credentials
| Storage | Readable by injected script (XSS)? | Sent automatically (CSRF risk)? | Verdict |
|---|---|---|---|
localStorage / sessionStorage | Yes: one XSS bug exfiltrates every token | No | Avoid for long-lived credentials |
| JS memory only | Yes, while the page is open | No | Acceptable for short-lived access tokens in SPAs |
Cookie with HttpOnly; Secure; SameSite | No: script cannot read it | Yes, but SameSite blocks most cross-site sends | Best default for sessions |
| Backend-for-frontend (BFF) | Tokens never reach the browser at all | Only the session cookie | Recommended for SPAs that use OAuth |
HTTP/1.1 200 OK
Set-Cookie: __Host-session=q9Xv2Lr8...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=86400- HttpOnly: JavaScript cannot read the cookie, so XSS cannot steal it (though it can still make requests while the page is open).
- Secure: sent only over HTTPS. See HTTP, HTTPS & TLS.
- SameSite=Lax: not sent on cross-site subrequests or cross-site POSTs, which defeats most CSRF.
Strictis tighter but drops the cookie when users arrive from an external link. __Host-prefix: the browser rejects the cookie unless it isSecure, hasPath=/and noDomain, so a compromised subdomain cannot overwrite it.
OAuth 2.0 and OpenID Connect
OAuth 2.0 is a framework for delegated authorization: letting an app act on a user's behalf at an API without ever seeing the user's password. OpenID Connect (OIDC) is a thin identity layer on top that adds a standard way to learn who logged in. "Sign in with Google" is OIDC; "let this app read your Google Drive" is OAuth.
- Resource owner
- The user who owns the data.
- Client
- The application requesting access: a web app, mobile app or backend job.
- Authorization server
- Authenticates the user, asks for consent and issues tokens (Okta, Auth0, Keycloak, Entra ID, Google).
- Resource server
- The API that accepts access tokens and serves the data.
- Scope
- A named permission the client asks for, such as
photos.read. The token carries only the scopes the user granted.
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic cGhvdG8tYXBwOnMzY3JldA==
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{"access_token":"eyJhbGciOiJFUzI1NiIs...","token_type":"Bearer","expires_in":900,
"refresh_token":"8xLOxBtZp8...","id_token":"eyJhbGciOiJFUzI1NiIs...","scope":"openid photos.read"}| Grant | Use it for | Status |
|---|---|---|
| Authorization code + PKCE | Any app acting for a user: web, SPA, mobile, desktop | The default for everything user-facing |
| Client credentials | Machine-to-machine calls with no user (cron jobs, backend services) | Current; prefer private-key JWT or mTLS client authentication over shared secrets |
| Device authorization | Input-constrained devices (TVs, CLIs): show a code, approve on a phone | Current (RFC 8628) |
| Refresh token | Renewing access tokens without user interaction | Current; rotate for public clients |
| Implicit | Formerly SPAs: tokens returned directly in the URL fragment | Deprecated by current security guidance and dropped from the OAuth 2.1 draft |
| Resource owner password | Formerly first-party apps: the client collects the password | Must not be used per current security guidance; dropped from OAuth 2.1 |
ID token (OIDC)
- Always a JWT, audience is the client
- Says who logged in, when and how (
sub,auth_time,amr,nonce) - The client reads it to start its own session
- Never send it to an API as a credential
Access token (OAuth)
- Opaque string or JWT, audience is the API
- Says what the bearer may do (scopes)
- The client should treat it as opaque and just forward it
- Short-lived; renewed with the refresh token
Storing passwords
Assume your user table will leak one day. Passwords must be stored so that a thief with the database still cannot recover them in bulk. That rules out encryption (the key leaks too) and fast hashes like SHA-256: they were designed to be fast. One high-end GPU tests on the order of ten billion SHA-256 guesses per second, against roughly a thousand for bcrypt at cost 12. Memory-hard functions like Argon2id go further: every guess needs its own block of RAM, which cripples the massive parallelism GPUs rely on.
| Algorithm | Property | Notes |
|---|---|---|
| Argon2id | Memory-hard, tunable time and parallelism | Winner of the 2015 Password Hashing Competition and the first choice in OWASP's guidance |
| scrypt | Memory-hard | Good alternative when Argon2 is unavailable |
| bcrypt | CPU-hard: 2^cost rounds, with cost from 4 to 31 | Battle-tested and everywhere; inputs are truncated or rejected beyond 72 bytes |
| PBKDF2 | Iterated HMAC, not memory-hard | Use when FIPS compliance requires it, with a very high iteration count |
| MD5, SHA-1, SHA-256 (even salted) | Fast | Never for passwords |
- Salt: a unique random value per password, stored next to the hash. It makes identical passwords hash differently and defeats precomputed rainbow tables. Modern libraries generate and embed it for you.
- Pepper (optional): a secret added to every hash and kept outside the database (in a secrets manager or HSM), so a database-only leak is not enough to start cracking.
- Tune and upgrade: pick parameters that take roughly 100 ms to 1 s on your servers, and rehash at the next login when you raise them.
- Compare in constant time and return the same error for "no such user" and "wrong password" so attackers cannot enumerate accounts.
- Modern policy: NIST's SP 800-63B guidance favors length over composition rules, recommends screening new passwords against lists of breached ones, and advises against forced periodic rotation, which pushes users toward predictable patterns like
Summer2026!.
MFA and passkeys
| Factor | How it works | Phishing-resistant? | Weakness |
|---|---|---|---|
| SMS / voice code | Code sent to a phone number | No | SIM swapping, interception, relay by a fake site |
| TOTP app | HMAC of a shared secret and the current 30 s step (RFC 6238) | No | A real-time phishing proxy can relay the code |
| Push approval | Tap approve in an app | No (better with number matching) | MFA fatigue: attackers spam prompts until the user taps yes |
| Security key / passkey (WebAuthn) | Device signs a server challenge with a private key bound to the site's domain | Yes | Account recovery becomes the weakest link |
WebAuthn (the browser API behind FIDO2) registers a key pair per site. The private key never leaves the authenticator; the server stores only the public key, so a database leak reveals nothing reusable. The browser binds every signature to the real origin, which is why a look-alike phishing domain cannot get a valid response. Passkeys are WebAuthn credentials that can sync across a user's devices through their platform's password manager, making phishing-resistant login usable as a password replacement rather than just a second factor.
Authorization models
| Model | Decision based on | Example rule | Fits |
|---|---|---|---|
| RBAC | Roles assigned to users | editor may update articles | Most business apps; easy to audit |
| ABAC | Attributes of user, resource, action and context | Doctors may read records of patients in their own department during their shift | Fine-grained, contextual rules |
| ReBAC | Relationships in a graph | You can view a doc if you are in a group that has access to its parent folder | Sharing models like Google Drive (Zanzibar, OpenFGA, SpiceDB) |
| ACL | Per-resource list of principals | Bucket reports grants read to alice | Simple resources, file systems |
- Least privilege: every user, service and API key gets only the permissions it needs, for as long as it needs them. Prefer short-lived, narrowly scoped credentials.
- Deny by default: an endpoint with no explicit rule rejects the request.
- Check ownership on every object:
GET /orders/1043must verify that order 1043 belongs to the caller. Missing this check (IDOR, or broken object-level authorization) is one of the most common API vulnerabilities. - Centralize policy, enforce locally: policy engines such as OPA or Cedar keep rules in one reviewable place while each service evaluates them in-process.
app.get("/orders/:id", requireAuth, async (req, res) => {
const order = await db.orders.findById(req.params.id);
// Same response for "missing" and "not yours": don't leak which IDs exist.
if (!order || (order.customerId !== req.user.id && !req.user.roles.includes("support"))) {
return res.status(404).json({ error: "not_found" });
}
res.json(order);
});Service-to-service authentication
Inside a microservice system, "it came from our private network" is not an identity. Zero trust means every service authenticates every caller, whatever network it arrived on. Two mechanisms dominate, and they are often combined.
Mutual TLS (mTLS)
- Both sides present certificates, so the server knows which workload is calling
- Identities like
spiffe://prod/ns/payments/sa/apiare issued and rotated automatically (SPIFFE/SPIRE, or a service mesh) - Encrypts traffic as a side effect
- Proves which service called, not which end user it is acting for
Signed tokens
- The caller attaches a short-lived JWT (client credentials grant, or a token exchanged from the user's)
- Carries end-user identity and scopes across hops
- Each service verifies signature and audience locally
- Must be scoped per audience so one service cannot replay it elsewhere
Secrets management
- Never commit secrets to source control or bake them into images. Run secret scanners (GitHub secret scanning, gitleaks) in CI, and treat any leaked secret as compromised: rotate it, don't just delete the commit.
- Use a secrets manager (HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) with access controlled by workload identity and every read audited.
- Prefer short-lived, dynamic credentials and automatic rotation over static keys that live for years.
- Envelope encryption: encrypt data with a data key, and encrypt the data key with a master key held in a KMS or HSM that never leaves it.
- Know your platform's defaults: Kubernetes Secrets are only base64-encoded in their manifests and are stored unencrypted in etcd unless encryption at rest is configured.
Defending against common attacks
The OWASP Top 10 is a regularly updated ranking of the most critical web application security risks, built from data across many organizations. Broken access control has held the top spot in recent editions; injection, cryptographic failures, misconfiguration and authentication failures are perennial entries. The table maps the attacks you are most likely to be asked about to their primary defenses.
| Attack | What happens | Primary defenses |
|---|---|---|
| Broken access control / IDOR | A user reads or changes another user's data by changing an ID | Deny by default, object-level checks on every request, tests for every role |
| SQL injection | Input is spliced into a query and executed as code | Parameterized queries everywhere, least-privilege DB accounts |
| Cross-site scripting (XSS) | Attacker-controlled script runs in your origin and acts as the user | Context-aware output encoding (frameworks escape by default), Content Security Policy, HttpOnly cookies |
| Cross-site request forgery (CSRF) | Another site makes the victim's browser send an authenticated request | SameSite cookies, anti-CSRF tokens, checking Origin on state-changing requests |
| Server-side request forgery (SSRF) | Your server is tricked into fetching an internal URL, such as the cloud metadata endpoint | Allowlist outbound destinations, block private and link-local ranges after DNS resolution, IMDSv2 |
| Credential stuffing | Leaked username and password pairs from other sites are tried at scale | MFA, breached-password checks, rate limiting, bot detection |
# VULNERABLE: email = "x' OR '1'='1" returns every user
cur.execute(f"SELECT id, name FROM users WHERE email = '{email}'")
# SAFE: the driver sends the value separately from the SQL text
cur.execute("SELECT id, name FROM users WHERE email = %s", (email,))- SQL injection: bound parameters can only ever be data, never SQL. ORMs parameterize for you, but raw-query escape hatches and dynamically chosen column or table names still need an allowlist, because identifiers cannot be bound as parameters.
- XSS: frameworks like React escape interpolated values by default, so most XSS today comes from escape hatches (
dangerouslySetInnerHTML,innerHTML,v-html),javascript:URLs and unsafe third-party scripts. A Content Security Policy (below) is the safety net: even if markup is injected, the browser refuses to run scripts that lack the per-response nonce. - CSRF only matters when credentials are sent automatically (cookies). With
SameSite=Laxcookies, state changes only via POST/PUT/DELETE, and anOrigincheck or CSRF token on those, it is largely solved. APIs authenticated purely byAuthorizationheaders are not exposed to it. - SSRF turns your server into the attacker's proxy. The 2019 Capital One breach used it to reach the cloud metadata service and steal role credentials. Validate destinations after DNS resolution (to defeat DNS rebinding), disable redirects or re-validate them, and require session-based metadata access such as AWS IMDSv2.
- Credential stuffing works because people reuse passwords. Rate limit login by account and by IP, add MFA, check passwords against breach corpora, and use risk signals (new device, impossible travel). See Rate Limiting.
Content-Security-Policy: script-src 'nonce-r4nd0m2026' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'Implementation
Use a vetted library with a memory-hard or deliberately slow algorithm. The library generates the salt and encodes the algorithm and parameters into the stored string, so you can raise the cost later and rehash on login.
# pip install argon2-cffi
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher() # Argon2id with the library's recommended defaults
def hash_password(password: str) -> str:
# Result looks like: $argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash>
return ph.hash(password)
def verify_password(stored_hash: str, password: str) -> tuple[bool, str | None]:
"""Returns (ok, new_hash_if_parameters_changed)."""
try:
ph.verify(stored_hash, password)
except VerifyMismatchError:
return False, None
if ph.check_needs_rehash(stored_hash):
return True, ph.hash(password) # upgrade to current parameters
return True, NoneKey takeaways
- Authentication proves who is calling; authorization decides what they may do, on every request and every object.
- Sessions revoke instantly but need a lookup; JWTs verify locally but cannot be recalled, so keep them short-lived and pair them with rotated refresh tokens.
- Use the authorization code flow with PKCE for anything user-facing and client credentials for machines; implicit and password grants are obsolete. OIDC's ID token is for the client, the access token is for the API.
- Hash passwords with Argon2id, scrypt or bcrypt (never a fast hash), and prefer phishing-resistant MFA such as passkeys.
- Zero trust inside the system: mTLS or signed tokens between services, least privilege everywhere, and short-lived secrets from a secrets manager.
- Most real breaches are broken access control, injection and stolen credentials: object-level checks, parameterized queries and MFA stop the bulk of them.
Common pitfalls
- Storing long-lived tokens in
localStorage, where any XSS bug can read them. - Verifying JWTs without pinning the algorithm or checking
audandiss, or issuing access tokens that live for days with no way to revoke them. - Checking that a user is logged in but not that the requested object belongs to them (IDOR).
- Hashing passwords with SHA-256 or MD5, even with a salt.
- Trusting every request from inside the network, so one compromised service can call anything.
Interview tips
- Be ready to compare sessions and JWTs on revocation, scalability and storage, and to propose the short access token plus rotated refresh token compromise.
- Walk through the authorization code flow with PKCE step by step, and explain what PKCE and
stateeach protect against. - When designing an API, say where tokens are validated (gateway and service), how object ownership is checked, and how login is rate limited.
Real-world applications
- "Sign in with Google/Apple/Microsoft" buttons: OIDC authorization code flows against those identity providers.
- Third-party integrations (Slack apps, GitHub Apps, Stripe Connect) requesting scoped OAuth access to user accounts.
- Service meshes such as Istio and Linkerd issuing and rotating workload certificates for automatic mTLS.
- Passkey sign-in offered by major platforms and password managers as a phishing-resistant replacement for passwords.
Test yourself
Why is a stolen JWT access token harder to deal with than a stolen session ID?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.