Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Stages build on each other, but once you have stages 1–6 you can take the rest in any order.
Stage 1 · Beginner Authentication fundamentals
Every login system, from a hobby app to enterprise single sign-on, is built from the same few ideas: who is the user, what proves it, and what the server does with that proof. Get the words and the basics right here, and every later stage is a variation on them.
Authentication vs authorization: identities, credentials and factors
Authentication (authn) answers "who are you?" and authorization (authz) answers "what are you allowed to do?". A login form is authentication; checking that the logged-in user may delete this invoice is authorization. They fail in different ways: an attacker who logs in as someone else broke authentication, while a normal user who reads another customer's order broke authorization. Many systems also keep an audit trail (who did what, when), the third "A" of AAA.
An identity is a set of attributes about a person or a program (a subject, often called a principal once it is logged in). An identifier such as an email or username says who you claim to be; a credential such as a password, a one-time code or a private key proves it. Credentials come from three kinds of factor: something you know (password, PIN), something you have (phone, security key, passkey) and something you are (fingerprint, face). Two of the same kind (password + security question) is still single-factor; multi-factor authentication needs two different kinds.
What to learn
- Authentication vs authorization vs auditing, with an example of each failing
- Identity, identifier, credential, subject and principal, and how they differ
- The three factor types, and why two passwords are still one factor
- Users vs machines: people log in, services authenticate with keys, certificates or tokens
- Where proof ends up: a session, a token or a signed assertion the app trusts afterwards
Free resources
Practice
Take three apps you use (a bank, an email account, a work tool). For each, write down the identifier, every credential it asks for, which factor type each one is, and one thing that is an authorization decision rather than authentication.
HTTP authentication: 401, 403, Basic and Bearer
HTTP has a built-in way to ask for credentials. When a request has none (or bad ones), the server answers 401 Unauthorized with a WWW-Authenticate header naming the scheme it expects; the client retries with an Authorization header. Despite its name, 401 means "not authenticated". 403 Forbidden means "I know who you are, and you still can't do this", which is an authorization failure.
The Basic scheme sends username:password Base64-encoded on every request. Base64 is not encryption, so Basic is only acceptable over HTTPS, and mostly for scripts and internal tools. Bearer (RFC 6750) sends a token instead: whoever holds ("bears") it gets in, so it must be kept as secret as a password. Digest is an old challenge-response scheme you'll meet only in legacy devices; modern apps use Bearer tokens or session cookies.
GET /api/orders HTTP/1.1
Host: shop.example
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="shop", error="invalid_token"
GET /api/orders HTTP/1.1
Host: shop.example
Authorization: Bearer eyJhbGciOiJFUzI1NiIsImtpZCI6IjEifQ...
HTTP/1.1 200 OK
What to learn
- The
WWW-Authenticate challenge and the Authorization header
- 401 vs 403, and why some APIs answer 404 to hide that a resource exists
- Basic authentication: how it is encoded and why it needs HTTPS
- Bearer tokens (RFC 6750) and the
invalid_token / insufficient_scope errors
- Why Digest and other legacy schemes are rarely used today
Free resources
Practice
Run curl -i https://httpbin.org/basic-auth/user/pass and look at the 401 and its challenge, then retry with -u user:pass and with -v to see the Authorization: Basic header. Decode the Base64 value by hand to prove it isn't encrypted.
Storing passwords: salted, slow hashes
Never store passwords, and never encrypt them either (whoever steals the key gets them all). Store a password hash made with an algorithm designed to be slow and memory-hungry, so that guessing billions of passwords after a database leak is impractical. OWASP's current advice: Argon2id (at least 19 MiB of memory, 2 iterations, 1 degree of parallelism); if that isn't available, scrypt (N = 217, r = 8, p = 1); bcrypt with a work factor of 10 or more for legacy systems (it only uses the first 72 bytes); and PBKDF2-HMAC-SHA256 with 600,000 iterations where FIPS-140 is required. Fast hashes such as SHA-256 or MD5 are wrong for passwords.
Each password gets its own random salt, stored next to the hash, so two users with the same password get different hashes and precomputed tables are useless. A pepper is an extra secret kept outside the database (in a vault or HSM), so a database dump alone isn't enough to crack anything. Compare hashes in constant time, and plan for upgrading parameters: store the algorithm and its settings with each hash and re-hash on the next successful login.
import hashlib
import hmac
import os
N, R, P = 2**17, 8, 1 # OWASP minimum for scrypt
MAXMEM = 256 * 1024 * 1024 # scrypt needs ~128 MiB here
def hash_password(password: str, salt: bytes) -> bytes:
return hashlib.scrypt(password.encode(), salt=salt,
n=N, r=R, p=P, maxmem=MAXMEM, dklen=32)
def verify(password: str, salt: bytes, stored: bytes) -> bool:
# compare_digest takes the same time whether or not bytes match
return hmac.compare_digest(hash_password(password, salt), stored)
salt = os.urandom(16) # a new random salt for every user
stored = hash_password("correct horse battery staple", salt)
print(len(salt), len(stored))
# prints 16 32
print(verify("correct horse battery staple", salt, stored))
# prints True
print(verify("Correct horse battery staple", salt, stored))
# prints False
other = hash_password("correct horse battery staple", os.urandom(16))
print(other == stored) # same password, different salt
# prints False
What to learn
- Why hashing, not encryption, and why fast hashes like SHA-256 fail for passwords
- Argon2id, scrypt, bcrypt and PBKDF2, with OWASP's minimum settings
- Salts (unique per password) vs peppers (one secret kept outside the database)
- Constant-time comparison, and bcrypt's 72-byte input limit
- Storing algorithm and parameters with each hash, and re-hashing on login to upgrade
- Use your framework's password encoder instead of writing this yourself
Free resources
Practice
Hash the same password with SHA-256 and with the scrypt example above, and time 1,000 attempts of each to see why slowness matters. Then add a "needs upgrade" check: store scrypt$N$r$p$salt$hash and re-hash when the stored N is lower than your current setting.
Account flows: sign-up, login, verification and password reset
Most account takeovers go through the flows around the login form, not the form itself. Sign-up should verify the email (or phone) with a single-use link before trusting it. Login should give the same answer and take about the same time whether the account exists or not, to avoid user enumeration. A password reset sends a random, single-use token that expires quickly (for example within an hour), is stored hashed, and logs the user out of other sessions once used; the reset page must not reveal whether an email is registered.
Modern password rules come from NIST SP 800-63B-4 (2025): at least 15 characters when a password is the only factor (8 when it is part of multi-factor login), allow at least 64 characters and any characters including spaces, check new passwords against a blocklist of common and breached passwords, and don't impose composition rules ("one upper case, one symbol") or force periodic changes; only force a change when there is evidence of compromise. Allow paste so password managers work.
What to learn
- Email verification and why an unverified email must not be trusted for login or account linking
- Generic error messages and equal timing to prevent user enumeration
- Secure reset tokens: random, single-use, short-lived, hashed at rest, sessions revoked after use
- NIST SP 800-63B-4 password rules: length, blocklist, no composition rules, no forced rotation
- Changing email or password requires the current password (re-authentication) and a notification
- Account deletion and the data it must remove
Free resources
Practice
Build sign-up, login and "forgot password" for a tiny app (any language). Store reset tokens hashed with a 30-minute expiry, make login return the same message for "no such user" and "wrong password", and write a test that measures both response times. Then try your own reset flow as an attacker: can you reuse a token, or use one after changing the password?
Identity assurance: NIST IAL, AAL and FAL
Not every login needs the same strength. The US NIST SP 800-63-4 guidelines (final in 2025, widely used outside government too) split confidence into three scales. IAL (identity assurance level) is how sure you are the person is who they claim to be at enrolment: IAL1 checks little, IAL2 and IAL3 involve identity proofing with evidence such as documents. AAL (authenticator assurance level) is how strong the login is: AAL1 allows a single factor, AAL2 needs two factors, AAL3 needs a phishing-resistant, hardware-backed authenticator. FAL (federation assurance level) is how securely an assertion travels from an identity provider to an app (see SSO).
The levels also set session limits: for example, re-authentication at least every 30 days at AAL1, every 24 hours (and after an hour idle) at AAL2, and every 12 hours (and after about 15 minutes idle) at AAL3. Use them as a vocabulary for risk decisions: a bank transfer might demand AAL2 with a fresh login, while reading a newsletter needs AAL1.
What to learn
- IAL, AAL and FAL, and which part of the user's journey each one covers
- What identity proofing is and when a service needs it
- AAL2 vs AAL3, and what "phishing-resistant" means at AAL3
- Re-authentication and inactivity limits per AAL
- Picking an assurance level from the impact of a wrong login (a risk assessment)
Free resources
Practice
For a made-up online pharmacy, list five actions (browse, order, view prescriptions, change delivery address, change email) and give each a required AAL and a maximum session age. Write one sentence per action explaining the harm if the wrong person did it.
Am I ready? Stage 1 quiz
A logged-in user requests another customer's invoice and the server refuses. Which status code fits best?
- 401 Unauthorized
- 403 Forbidden
- 400 Bad Request
- 407 Proxy Authentication Required
The user is authenticated but not allowed: that's 403 (or a deliberate 404 to hide the invoice). 401 means the request has no valid credentials.
A login asks for a password and then the answer to a security question. How many factors is that?
- Two, because there are two prompts
- Three, counting the username
- Two, if the answers are long enough
- One: both are "something you know"
Multi-factor means different kinds of factor. A password plus a security question are both knowledge, so it is still single-factor.
What is the purpose of a unique salt per password?
- Same passwords get different hashes, so precomputed tables and bulk cracking stop working
- It makes the hash reversible for support staff
- It replaces the need for a slow hashing algorithm
- It encrypts the hash with a secret key
Salts aren't secret; they make every hash unique. You still need a slow algorithm such as Argon2id so each guess is expensive.
Which password rule follows NIST SP 800-63B-4?
- Require one upper-case letter, one digit and one symbol
- Force everyone to change passwords every 90 days
- Check new passwords against a list of common and breached passwords
- Block pasting into the password field
NIST asks for length and a blocklist, and says not to impose composition rules or periodic changes. Blocking paste hurts password managers.
Stage 2 · Beginner Session and cookie authentication
The classic web login: the server checks the password once, then remembers the user with a session and a cookie. It is still the simplest and often the safest choice for a website, as long as the cookie, the session's lifetime and cross-site requests are handled properly.
Server-side sessions
HTTP is stateless, so after a successful login the server creates a session: a record (user id, login time, roles, maybe a CSRF token) kept in memory, a database or a cache, looked up by a long random session id. The id goes to the browser in a cookie, and the browser sends it back on every request. The id itself means nothing; all the facts stay on the server, so you can change or delete a session at any time and the user is instantly logged out.
The session id is as good as a password while it lives. Generate it with a cryptographically secure random generator with at least 64 bits of entropy (OWASP's minimum; frameworks use more), never put it in URLs, and never accept an id the server didn't create. Use your framework's session support rather than building your own.
1. Browser → POST /login (email + password)
2. Server → checks the password hash, creates session
sessions["k3Jx…9Qa"] = {user: 42, created: 10:00}
3. Server → 303 See Other
Set-Cookie: __Host-sid=k3Jx…9Qa; Secure; HttpOnly;
SameSite=Lax; Path=/
4. Browser → GET /orders Cookie: __Host-sid=k3Jx…9Qa
5. Server → looks up the session → user 42 → 200 OK
6. Logout → server deletes sessions["k3Jx…9Qa"]
What to learn
- Why HTTP needs sessions, and what a session record usually holds
- Session ids: secure random, at least 64 bits of entropy, meaningless on their own
- Where sessions live: memory, database or cache, and what happens on a restart
- Why the server can revoke a session instantly, and why that matters
- Never accept session ids from URLs or ids the server didn't issue
Free resources
Practice
Build a login with server-side sessions in the framework you know. Open DevTools, find the session cookie, then delete the session on the server (or restart an in-memory store) and confirm the next request is logged out. Copy the cookie into another browser profile and see that it logs you in there too: that is why it must be protected.
Cookie security: HttpOnly, Secure, SameSite and prefixes
A session cookie needs a handful of attributes. Secure sends it over HTTPS only. HttpOnly hides it from JavaScript, so an XSS bug can't simply read and steal it (it can still act as the user while the page is open). SameSite controls cross-site sending: Strict never sends it from other sites, Lax sends it on top-level navigations such as following a link, and None (which requires Secure) always sends it. Chrome treats cookies without the attribute as Lax, but set it explicitly.
Keep the scope narrow. Leaving out Domain makes a host-only cookie that subdomains can't read or overwrite. The __Host- name prefix makes the browser enforce this: such a cookie must be Secure, have Path=/ and no Domain, so a compromised blog.example.com can't plant a session cookie for example.com. Without Expires/Max-Age a cookie is a session cookie, though browsers that restore tabs may keep it. The web security roadmap's cookies and sessions topic shows the attacks these attributes stop.
Set-Cookie: __Host-sid=k3Jx9Qa; Path=/; Secure; HttpOnly; SameSite=Lax
What to learn
Secure, HttpOnly and what HttpOnly does and doesn't stop
SameSite=Strict, Lax and None, and "site" vs "origin"
Domain and Path, host-only cookies, and why wide domains are risky
- The
__Host- and __Secure- prefixes and the rules browsers enforce for them
- Session vs persistent cookies (
Expires, Max-Age)
Free resources
Practice
Set the same cookie four ways (no attributes, HttpOnly, SameSite=Strict, __Host- with a Domain) from a local app. Check in DevTools which ones document.cookie can read, which one the browser rejects, and which are sent when you follow a link from another local site on a different port and host name.
Session lifecycle: fixation, timeouts, logout and remember-me
Session fixation: if an attacker can make a victim use a session id the attacker knows, and the app keeps that id after login, the attacker is now logged in too. The fix is simple: issue a new session id on login (and on any privilege change, such as entering an admin area). Every session also needs two timeouts: an idle timeout (no requests for a while) and an absolute timeout (maximum age, however active). Short ones for banking, longer for low-risk apps.
Logout must destroy the session on the server, not just delete the cookie. Offer "log out of all devices" and do it automatically after a password change. Remember-me should be a separate, long-lived, random token stored hashed on the server, that creates a fresh session when used and is rotated each time; sensitive actions should still ask for the password again (re-authentication).
What to learn
- Session fixation and regenerating the session id after login
- Idle vs absolute timeouts, and choosing values by risk
- Server-side logout, "log out everywhere", and ending sessions after a password reset
- Remember-me tokens done safely (random, hashed, rotated, revocable)
- Re-authentication before sensitive actions such as changing email or payout details
- A session list page where users can see and end their sessions
Free resources
Practice
In your session-based app, note the session id before and after login: if it is the same, fix it. Add a 15-minute idle timeout and an 8-hour absolute timeout, a "log out of all devices" button, and make a password change end every other session. Write a test for each.
CSRF: cross-site request forgery
Because the browser attaches cookies automatically, another site can make the victim's browser send a request to yours, for example a hidden form that posts to /transfer, and your server sees a valid session. That is CSRF. Any app that authenticates with cookies must defend against it; APIs that only accept a token in the Authorization header aren't affected, because browsers don't add that header by themselves.
Layer the defences: SameSite=Lax or Strict cookies; an anti-CSRF token (a random value tied to the session that every state-changing form or request must include, the "synchronizer token" pattern, which frameworks provide); checking the Origin header or the Fetch Metadata header Sec-Fetch-Site and rejecting cross-site state changes; and never changing state on GET.
What to learn
- How a CSRF attack works with an auto-submitting form, and why cookies make it possible
- Synchronizer tokens and the signed double-submit cookie pattern
- What
SameSite protects, and its gaps (same-site subdomains, top-level GET with Lax)
- Checking
Origin and Sec-Fetch-Site on state-changing requests
- Why header-token APIs are not exposed to CSRF but cookie-based SPAs are
Free resources
Practice
Add a "change email" form to your session app without CSRF protection, and attack it from a second local site with an auto-submitting form. Then add your framework's CSRF tokens plus an Origin check and confirm the attack fails. The web security roadmap's CSRF topic has free labs.
Sessions at scale: shared stores and sticky sessions
With one server, sessions can live in memory. With several behind a load balancer, a request may land on a server that never saw the login. Two answers: sticky sessions (the load balancer always sends a user to the same server, simple but users are logged out when that server dies) or a shared session store that every server reads, usually Redis or a database. A shared store is the normal choice: sessions survive deploys, and logout or "end all sessions" works everywhere at once.
Libraries do the plumbing: Spring Session, connect-redis for Express, Django's cache or database session backends. Give stored sessions a TTL that matches the absolute timeout, keep them small (ids and a few claims, not whole user objects), secure the store like a database (network access, authentication, TLS), and index sessions by user id so you can revoke them all. The next stage compares this with stateless tokens.
What to learn
- Why in-memory sessions break behind a load balancer
- Sticky sessions vs a shared session store, and the failure mode of each
- Redis as a session store: TTLs, eviction settings, persistence and high availability
- Finding and deleting all sessions of one user (a secondary index)
- Protecting the session store: private network, authentication, TLS
Free resources
Practice
Run two copies of your app behind a simple proxy (nginx or Caddy, round-robin) with in-memory sessions and watch logins "randomly" fail. Move sessions to Redis in Docker, then add "log out of all devices" that deletes every session of a user across both copies. See the Redis roadmap's caching patterns and security topics.
Am I ready? Stage 2 quiz
What is the main fix for session fixation?
- Set the
HttpOnly flag on the session cookie - Make the session id longer
- Issue a new session id when the user logs in
- Store sessions in Redis instead of memory
Fixation works when the pre-login id survives login. Regenerating the id on login (and on privilege changes) makes the attacker's known id useless.
Which rule does a cookie named __Host-sid have to follow?
- It must be
Secure, have Path=/ and no Domain attribute - It must be
HttpOnly and SameSite=Strict - It must expire within one hour
- It can only be set by JavaScript
The __Host- prefix pins the cookie to one host over HTTPS, so subdomains can't set or overwrite it. HttpOnly and SameSite are still separate choices.
An API reads its access token only from the Authorization header and never from cookies. Why is it not exposed to classic CSRF?
- Because HTTPS encrypts the request
- Because APIs only accept JSON
- Because tokens expire quickly
- Because browsers don't attach that header to cross-site requests on their own
CSRF relies on credentials the browser adds automatically, like cookies. A header that only your own JavaScript sets can't be forged by another site.
You run four app servers behind a load balancer. Which session setup lets "log out of all devices" work instantly and survive a server crash?
- In-memory sessions with sticky sessions
- A shared session store such as Redis
- Storing the user id in a plain cookie
- Longer idle timeouts
With a shared store every server sees the same sessions, so deleting them takes effect everywhere. Sticky in-memory sessions are lost with their server.
Stage 3 · Beginner → Intermediate Token-based authentication
APIs, mobile apps and other services usually don't use cookies; they send a token with each request. Learn the main kinds of token, how long they should live, how to refresh and revoke them, and where a browser app can keep one safely.
Tokens vs sessions: stateful and stateless
A token is a string the client sends (usually as Authorization: Bearer …) to prove it is logged in. There are two families. A reference (opaque) token is a random id the server looks up, exactly like a session id, just sent in a header. A self-contained token such as a JWT carries the user id, expiry and permissions inside it, signed by the issuer, so any service with the key can check it without a lookup.
Self-contained tokens scale easily across services but are hard to revoke before they expire; reference tokens and sessions are easy to revoke but need a lookup on every request. Neither is "more secure" by default. For a classic website a session cookie is usually simplest; tokens fit APIs called by mobile apps, other services and third parties, and they are what OAuth issues.
What to learn
- Reference (opaque) tokens vs self-contained tokens
- Stateful vs stateless checking, and the cost of each (lookup vs revocation)
- Cookies vs the
Authorization header as the way to send a credential
- When to pick sessions, opaque tokens or JWTs for a website, a mobile app and a public API
- Why "stateless JWTs instead of sessions" is often the wrong reason to use JWTs
Free resources
Practice
Write a one-page decision note for three clients of the same backend: the company website, its iPhone app and a partner's server. For each, choose session cookie, opaque token or JWT, and explain how you would revoke access within one minute if the account were compromised.
API keys
An API key is a long-lived secret that identifies a project or integration rather than a person, sent in a header such as Authorization or X-API-Key. Keys are simple and fine for server-to-server calls, but they never expire on their own, so treat them like passwords. Generate at least 128 bits of secure randomness, show the key once, and store only a hash of it (a fast hash such as SHA-256 is fine here, because the key is random, not a human password).
Good key design: a recognisable prefix (GitHub tokens start with ghp_, Stripe secret keys with sk_live_) so leaked keys can be found by secret scanning; a short visible id to tell keys apart in the UI; scopes and optional IP limits; expiry dates; rotation with an overlap period; and per-key rate limits and logs. A key in a mobile app or front-end code is public: use it only to identify an app, never to protect data.
What to learn
- When API keys fit (server-to-server, identifying a project) and when they don't (user login, browsers)
- Generating keys with a CSPRNG and storing only a hash
- Prefixes and checksums that make leaked keys detectable by secret scanners
- Scopes, expiry, rotation with two active keys, and instant revocation
- Rate limiting and logging per key
Free resources
Practice
Add API keys to a small API: generate myapp_live_ + 32 random bytes in base62, store only sha256(key) plus a 6-character display id, check keys with a constant-time comparison, and support two active keys per client so they can rotate without downtime. Log the key id (never the key) on every request.
Opaque tokens and token introspection
An opaque (reference) token is a random string with no meaning to the client or the API. To check it, the API asks the issuer. In OAuth this is token introspection (RFC 7662): the resource server POSTs the token to the authorization server's introspection endpoint, authenticating itself, and gets back JSON with active and details such as sub, scope, client_id and exp. If the token was revoked a second ago, active is already false.
The trade-off is a network call per request, so APIs often cache introspection results for a short time (seconds to a minute), which delays revocation by that much. Opaque tokens also keep personal data out of the token: nothing about the user can leak from a log line or a browser.
POST /oauth2/introspect HTTP/1.1
Host: auth.example
Authorization: Basic YXBpLXNlcnZlcjpzM2NyM3Q=
Content-Type: application/x-www-form-urlencoded
token=mF_9.B5f-4.1JqM
HTTP/1.1 200 OK
Content-Type: application/json
{"active": true, "sub": "user-42", "client_id": "shop-web",
"scope": "orders:read", "exp": 1798761600}
What to learn
- What makes a token opaque, and why clients must never parse access tokens anyway
- The RFC 7662 introspection request and response, and how the API authenticates to it
- Caching introspection results and the revocation delay it causes
- Token revocation (RFC 7009) for logout
- Opaque vs JWT access tokens: latency, revocation and privacy
Free resources
Practice
Implement a tiny token service: /login issues a random 32-byte token stored (hashed) with a user id and expiry, /introspect returns RFC 7662-style JSON, and /revoke deletes it. Make a second API that calls /introspect with a 30-second cache, then measure how long a revoked token keeps working.
Access tokens, refresh tokens and rotation
Short-lived access tokens (often 5 to 60 minutes) go to every API call, so if one leaks it is only useful briefly. A long-lived refresh token goes only to the authorization server, to get a new access token without asking the user to log in again. That split gives you both short exposure and a long login.
Refresh tokens are valuable, so protect them. Rotation issues a new refresh token every time one is used and invalidates the old one; with reuse detection, if an old one is ever presented again, someone stole it, so the server revokes the whole token family and the user must log in again. The OAuth security best practice (RFC 9700) requires refresh tokens for public clients (browser and mobile apps) to be either rotated like this or sender-constrained (see DPoP and mTLS). Also set an absolute lifetime and an idle limit, and revoke all of a user's refresh tokens on password change.
login → access A1 (15 min) + refresh R1
A1 expires → POST /token refresh_token=R1
← access A2 + refresh R2 (R1 now invalid)
attacker uses R1 → server sees a reused token
→ revokes R2 and the whole family; user logs in again
What to learn
- Why access tokens are short-lived and refresh tokens long-lived
- The refresh request and where each token is sent
- Refresh token rotation, token families and reuse detection
- Absolute vs idle (sliding) refresh lifetimes
- Revoking refresh tokens on logout, password change and suspicious activity
Free resources
Practice
Extend your token service with refresh tokens: 10-minute access tokens, rotating refresh tokens grouped in families, and reuse detection that revokes the family. Write a test that plays the attacker: use R1 after the real client has already swapped it for R2, and check that both stop working.
Storing tokens in the browser
Single-page apps must keep tokens somewhere, and every choice has a cost. localStorage / sessionStorage survive reloads, but any script on the page can read them, so one XSS bug (or a compromised npm package) can copy the tokens to the attacker, who then uses them from anywhere until they expire. In-memory storage (a JavaScript variable) is harder to steal but lost on reload. An HttpOnly cookie can't be read by scripts at all, but brings back CSRF and cookie scoping.
Remember that XSS is game over either way: an attacker's script can call your API as the user while the page is open. What storage changes is whether tokens can be stolen and reused later. That is why the IETF's guidance for browser apps (RFC 10017, 2026) prefers a backend-for-frontend (BFF): the server does the OAuth work, keeps the tokens, and gives the browser only an HttpOnly session cookie. If tokens must live in the browser, keep them in memory, short-lived, and sender-constrained where possible.
What to learn
- localStorage vs sessionStorage vs memory vs HttpOnly cookies: what each exposes
- What XSS can do with each option (steal vs act as the user)
- Why the BFF pattern keeps tokens out of the browser
- Content Security Policy and dependency hygiene as the real XSS defences
- Silent refresh, short lifetimes and logout in a single-page app
Free resources
Practice
Build a tiny SPA that stores a dummy token in localStorage, then "inject" a script in DevTools that reads it and posts it elsewhere. Move the token to an HttpOnly cookie set by a small backend and repeat: the script can no longer read it, but can still call the API from the page. Write down what changed and what didn't. The web security roadmap's XSS topic covers the defences.
Am I ready? Stage 3 quiz
How should a server store the API keys it issues?
- In plain text, so support can read them to customers
- As a hash, showing the full key to the customer only once
- Encrypted with a key in the same database
- Only in the customer's browser
Like passwords, keys stored as hashes are useless to someone who steals the database. Because keys are long and random, a fast hash such as SHA-256 is enough.
What does refresh token reuse detection do when an already-used refresh token comes back?
- Returns the same new access token again
- Ignores the request
- Extends the token's lifetime
- Treats it as theft and revokes the whole token family
With rotation, a used refresh token should never appear again. If it does, either the client or an attacker has a copy, so the safe move is to revoke them all.
What is the main advantage of opaque tokens checked by introspection over self-contained JWTs?
- Revocation takes effect immediately (apart from any short cache)
- No network call is needed to validate them
- They can be read by the client app
- They never expire
The issuer is asked each time, so a revoked token is inactive at once. The cost is a lookup per request, which JWTs avoid.
A single-page app keeps its access token in localStorage. What can an XSS bug do that it couldn't if the token were only in an HttpOnly cookie managed by a BFF?
- Call the API as the user while the page is open
- Read the page's HTML
- Copy the token and reuse it from the attacker's own machine later
- Change what the user sees
XSS can act as the user in both cases. Script-readable storage additionally lets the attacker steal the token and use it elsewhere until it expires.
Stage 4 · Intermediate JWT (JSON Web Tokens)
JWTs are everywhere: OAuth access tokens, OpenID Connect ID tokens, service-to-service calls. They are simple to read and easy to get wrong, so learn exactly what is inside one, how signatures work, and the checks every server must make.
Inside a JWT: header, payload, signature and claims
A JWT (RFC 7519) is three base64url parts joined by dots: a header (JSON naming the algorithm, alg, and often a key id, kid), a payload of claims (JSON facts about the subject), and a signature over the first two parts. Base64url is just encoding: anyone holding the token can read the payload, so never put secrets or more personal data than needed in it. The signature only proves the content wasn't changed and who issued it.
The registered claims you'll meet constantly: iss (issuer), sub (subject, the user or client id), aud (audience, who the token is for), exp (expiry), nbf (not before), iat (issued at) and jti (unique token id). Times are seconds since 1970 (Unix time). Everything else is a custom claim such as scope or roles.
import base64
import json
# The example token from RFC 7515, Appendix A.1 (split over lines)
token = (
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9"
".eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt"
"cGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
".dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
)
def b64url_decode(part: str) -> bytes:
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
header, payload, signature = token.split(".")
print(json.loads(b64url_decode(header)))
# prints {'typ': 'JWT', 'alg': 'HS256'}
print(json.loads(b64url_decode(payload)))
# prints {'iss': 'joe', 'exp': 1300819380, 'http://example.com/is_root': True}
print(len(b64url_decode(signature)), "signature bytes")
# prints 32 signature bytes
What to learn
- The three parts of a JWT and base64url encoding (no padding,
- and _)
- Registered claims:
iss, sub, aud, exp, nbf, iat, jti
- Header fields:
alg, typ, kid
- Decoding is not verifying: anyone can read and craft the payload
- Keeping tokens small and free of secrets and unnecessary personal data
Free resources
Practice
Paste the token from the example into the JWT decoder, then log in to any app you own that uses JWTs and decode its token: list every claim, convert exp and iat to dates, and work out the token's lifetime. Change one character of the payload and see that the decoder still shows it but the signature no longer matches.
Signing JWTs: HMAC vs public keys, JWKS and key ids
A signed JWT is a JWS (RFC 7515). With HS256 (HMAC-SHA256) the same shared secret signs and verifies, so every service that can check tokens can also forge them: fine inside one application, risky across many. With asymmetric algorithms, RS256 (RSA), ES256 (ECDSA P-256) or EdDSA (Ed25519), only the issuer holds the private key and everyone else verifies with the public key. That is the norm for identity providers and anything crossing service boundaries.
Issuers publish public keys as a JWK Set (RFC 7517) at a jwks_uri. Each key has a kid; the token header names the kid it was signed with, so keys can be rotated by publishing the new key before using it. HMAC secrets must be random and at least as long as the hash output (32 bytes for HS256), never a word like "secret". The example reproduces the HS256 signature from RFC 7515.
import base64
import hashlib
import hmac
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def b64url_decode(part: str) -> bytes:
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
# Key and signing input from RFC 7515, Appendix A.1
key = b64url_decode(
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T"
"-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow")
header = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9"
payload = ("eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9l"
"eGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ")
signing_input = f"{header}.{payload}".encode()
def sign(data: bytes) -> str:
return b64url(hmac.new(key, data, hashlib.sha256).digest())
signature = sign(signing_input)
print(signature)
# prints dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
def verify(token: str) -> bool:
h, p, s = token.split(".")
expected = sign(f"{h}.{p}".encode())
return hmac.compare_digest(expected, s)
print(verify(f"{header}.{payload}.{signature}"))
# prints True
tampered = payload.replace("jE", "jF", 1) # change a byte of the claims
print(verify(f"{header}.{tampered}.{signature}"))
# prints False
What to learn
- JWS signing input (
header.payload) and how the signature is computed
- HS256 vs RS256 vs ES256 vs EdDSA, and who can forge tokens with each
- JWK and JWK Set documents, the
jwks_uri, and the kid header
- Secret strength for HMAC keys, and keeping private keys in a KMS or HSM
- Using a maintained JWT library instead of hand-written signing in production
Free resources
Practice
Run the example, then use a JWT library in your language to sign the same claims with ES256: generate a key pair, publish the public key as a JWKS JSON file with a kid, and verify the token in a second program that only reads the JWKS. Finally, add a second key and switch signing to it without breaking tokens signed with the first.
Validating JWTs safely
Most JWT vulnerabilities come from incomplete validation. Follow the JWT best current practice (RFC 8725). Pin the algorithms you accept on the server; never let the token's own alg decide. Otherwise attackers send alg: none (no signature) or perform algorithm confusion: sign with HS256 using your RSA public key as the HMAC secret, which a naive library will accept. Don't trust keys or key URLs from the token header (jwk, jku, x5u) either.
After the signature, check the claims: iss is your expected issuer, aud contains your API (so a token for another service is rejected), exp and nbf with a small clock-skew allowance (a minute or so), and the token type, so an ID token can't be used as an access token (RFC 9068 access tokens carry typ: at+jwt). Then apply authorization using the scopes or roles. Good libraries do all this when configured with the issuer, audience and algorithm list.
What to learn
- The validation order: parse, choose the key by
kid, verify the signature with an allowed algorithm, then check claims
alg: none, algorithm confusion, and why the server must pin algorithms
- Untrusted header parameters:
jwk, jku, x5u and kid injection
- Checking
iss, aud, exp, nbf and clock skew
- Explicit token types so ID tokens, access tokens and other JWTs can't be swapped
- Brute-forcing weak HMAC secrets offline, and why long random secrets matter
Free resources
Practice
Write a validation test suite for your API: a valid token passes; tokens with alg: none, an HS256 signature made with your public key, a wrong aud, a wrong iss, an exp two minutes ago and an ID token instead of an access token are all rejected with 401. Then do the PortSwigger JWT labs. The web security roadmap's JWT security topic goes further.
Expiry, revocation and logout with JWTs
A self-contained JWT stays valid until exp, even after the user logs out, changes their password or is fired. The main defence is a short lifetime (minutes) plus refresh tokens that can be revoked centrally, so access ends within one access-token lifetime. When that isn't fast enough, add state back deliberately.
Options: a denylist of revoked jti values kept until their exp (small, because tokens are short-lived; often in Redis); a per-user token version or "valid after" timestamp checked against iat, which logs a user out everywhere in one write; or switching to opaque tokens with introspection for high-risk APIs. Every one of them adds a lookup, which is fine: just be honest that the system is no longer fully stateless.
What to learn
- Why JWTs can't be "deleted", and what logout really means with them
- Choosing access-token lifetimes by risk
- A
jti denylist with a TTL equal to the remaining token lifetime
- Per-user token versions or "not before" timestamps for "log out everywhere"
- When to switch to opaque tokens or sessions instead
Free resources
Practice
Add "log out" and "log out everywhere" to a JWT-protected API: logout stores the token's jti in Redis with a TTL of exp − now; "everywhere" bumps a token_version on the user that every request compares with a claim in the token. Measure the extra latency per request.
Encrypted JWTs (JWE), nested tokens and alternatives such as PASETO
A normal JWT is signed but readable. A JWE (RFC 7516) is encrypted: it has five parts and only the holder of the right key can read the claims. It is useful when a token passes through the browser but contains data the client shouldn't see. To be both confidential and verifiable, sign first and then encrypt the signed JWT (a nested JWT). Most of the time an opaque token is simpler than JWE.
The flexibility of JOSE (many algorithms, keys in headers) is what made JWT attacks possible, so alternative formats remove choices. PASETO uses versioned "protocols" with one fixed algorithm suite each, with local (encrypted) and public (signed) purposes. Others, such as Biscuit or macaroons, add offline attenuation. JWT remains the standard that OAuth and OpenID Connect require, so learn these as options, not replacements.
What to learn
- JWS vs JWE, and the five parts of a compact JWE
- Key management algorithms vs content encryption (for example
RSA-OAEP-256 + A256GCM)
- Nested JWTs: sign, then encrypt
- PASETO's versioned protocols and its
local vs public purposes
- When JWE is worth it vs an opaque reference token
Free resources
Practice
With a JOSE library, create a JWE containing an email address, show that the JWT decoder can't read its payload, and decrypt it with the private key. Then make a nested token (signed, then encrypted) and write down which side needs which key.
Am I ready? Stage 4 quiz
A JWT's payload contains the user's email. Who can read it?
- Only the server that holds the signing key
- Only the authorization server
- Anyone who has the token, because the payload is only base64url-encoded
- Nobody, because it is hashed
A signed JWT is not encrypted. The signature stops changes, not reading. Use JWE or an opaque token if the content must stay private.
How do you stop an algorithm-confusion attack where an RS256 token is re-signed as HS256 with your public key?
- Configure the server to accept only RS256 for that issuer, whatever the header says
- Make the RSA key longer
- Shorten the token lifetime
- Base64-encode the public key
The attack works when the library lets the token's alg pick how to verify. Pinning the expected algorithm (and key type) closes it.
Why do many systems prefer RS256 or ES256 over HS256 for tokens checked by several services?
- They produce smaller tokens
- Verifiers only need the public key, so they can't mint tokens
- They don't need an
exp claim - They are encrypted, not just signed
With HMAC every verifier holds the signing secret and could forge tokens. With asymmetric keys only the issuer can sign.
A user clicks "log out everywhere" in an app that uses 15-minute JWT access tokens. What makes it take effect immediately?
- Deleting the token from the browser's localStorage
- Making access tokens last 24 hours instead
- Changing the
sub claim format - A per-user token version (or revoked-
jti list) checked on each request
Without a server-side check, a copied JWT keeps working until it expires. A small piece of state, such as a token version, lets you cut it off at once.
Stage 5 · Intermediate OAuth 2.0
OAuth 2.0 is how one application gets limited access to an API on a user's behalf without ever seeing their password. Learn the roles, the authorization code flow with PKCE, scopes, the other grant types and the current security best practice.
OAuth 2.0 basics: delegation and the four roles
Before OAuth, a photo-printing site that wanted your pictures would ask for your email password. OAuth replaces that with delegated access: you log in at the service that holds your data, approve a limited request ("read your photos"), and the printing site receives an access token that works only for that, only for a while, and can be revoked without changing your password.
There are four roles. The resource owner is the user. The client is the app that wants access. The authorization server (AS) logs the user in, asks for consent and issues tokens. The resource server (RS) is the API that accepts the tokens. One important point: OAuth is about authorization, not authentication. An access token says "the bearer may call this API", not "this person is logged in to your app"; using it as a login is a classic mistake. Logging users in is what OpenID Connect adds on top. The core spec is RFC 6749, and RFC 6750 defines how to send a bearer token (Authorization: Bearer …).
What to learn
- The problem OAuth solves: sharing passwords with third-party apps
- The four roles: resource owner, client, authorization server, resource server
- Access tokens, refresh tokens, scopes and grant types as vocabulary
- The authorization endpoint (in the browser) vs the token endpoint (back channel)
- Why an access token is not proof of login, and where OpenID Connect fits
Free resources
Practice
Open the OAuth 2.0 Playground and walk through the authorization code flow. At each step write down which of the four roles is talking to which, and whether the message goes through the browser (front channel) or server to server (back channel).
Authorization code flow with PKCE
This is the flow to use for almost every app that has a user: web apps, single-page apps and mobile apps. The browser is sent to the authorization server, the user logs in and consents, and the browser comes back to your redirect URI with a short-lived, one-time authorization code. Your app then swaps the code for tokens at the token endpoint, over a direct back-channel request, so tokens never sit in the browser's address bar or history.
PKCE (RFC 7636, "pixy") protects that swap. Before redirecting, the client makes a random code_verifier, sends only its SHA-256 hash (code_challenge) in the first request, and must present the original verifier when redeeming the code. An attacker who intercepts the code can't use it without the verifier. PKCE was first designed for mobile apps, but current best practice requires it for every client, including confidential server-side ones. The state parameter (or PKCE) also stops an attacker from injecting their own code into your callback (login CSRF).
Browser Client app Authorization server API
| 1. click "Log in" | | |
|------------------->| make verifier, challenge, state |
| 2. 302 to /authorize?response_type=code&client_id=... |
| &redirect_uri=...&scope=...&state=... |
| &code_challenge=...&code_challenge_method=S256 |
|--------------------------------------->| 3. log in + consent |
| 4. 302 to redirect_uri?code=...&state=... |
|------------------->| 5. check state | |
| | 6. POST /token: code + code_verifier |
| |------------------->| hash(verifier) |
| | | == challenge? |
| |<-------------------| 7. access token |
| | 8. GET /photos Authorization: Bearer |
| |-------------------------------------->|
import base64
import hashlib
import secrets
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def new_verifier() -> str:
# 32 random bytes -> 43 URL-safe characters (allowed: 43 to 128)
return b64url(secrets.token_bytes(32))
def challenge(verifier: str) -> str:
return b64url(hashlib.sha256(verifier.encode("ascii")).digest())
print(len(new_verifier()))
# prints 43
# The test vector from RFC 7636 Appendix B:
print(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"))
# prints E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
What to learn
- Every parameter of the authorization request:
response_type, client_id, redirect_uri, scope, state
- The callback: checking
state, handling error responses, and exchanging the code
- PKCE:
code_verifier, code_challenge and why only S256 should be used
- Why codes are short-lived and single-use, and why the exchange happens on the back channel
- Native and mobile apps: the system browser, claimed HTTPS links or custom schemes (RFC 8252)
Free resources
Practice
Run a local Keycloak (or use a free developer tenant of any provider), register a public client, and do the whole flow by hand: build the /authorize URL with a PKCE challenge in a browser, copy the code from the redirect, then redeem it with curl at the token endpoint. Try redeeming the same code twice, and once with a wrong verifier, and read the errors.
Scopes, consent and audience
A scope is a named permission the client asks for, such as photos.read or calendar.write. The user sees the requested scopes on the consent screen, and the token records what was granted (which can be less than what was asked). The API then checks that the token carries the scope a request needs. Ask for the smallest set that works, and ask for more later ("incremental consent") when the user actually uses a feature.
Scopes say what; the audience says where. A token meant for the photos API should be rejected by the billing API, so tokens carry an aud value and every API checks it. Resource indicators (RFC 8707) let a client name the API it wants a token for with a resource parameter, so the authorization server can issue narrowly targeted tokens. Remember that scopes describe what the client may do on the user's behalf; they don't replace your own checks of what the user may do (see enforcing authorization).
What to learn
- Designing scope names (resource + action) and keeping them coarse enough to be understood
- Consent screens, granted vs requested scopes, and incremental consent
- The
aud claim and why every API must check it
- Resource indicators (RFC 8707) for clients that call several APIs
- The difference between client scopes and user permissions
Free resources
Practice
Design the scopes for a small notes API (read notes, write notes, share notes, admin). Request a token with only the read scope, decode it, and make your API return 403 with WWW-Authenticate: Bearer error="insufficient_scope" when that token tries to write.
Other grants and client types
A grant type is a way to get a token. Besides the authorization code there are three you'll meet. The refresh token grant swaps a refresh token for a new access token without bothering the user (see access and refresh tokens). The device authorization grant (RFC 8628) is for TVs, consoles and CLIs that have no good browser: the device shows a short code, and the user approves it on their phone. Client credentials is for a service acting as itself, with no user (covered in machine-to-machine authentication).
Two old grants are now deprecated. The implicit grant returned tokens straight in the URL fragment, where they leaked through history, logs and referrers; single-page apps now use code + PKCE instead. The resource owner password grant had the app collect the user's password, which defeats the point of OAuth and blocks MFA and passkeys. Clients also come in two kinds: confidential clients run on a server and can keep a secret; public clients (SPAs, mobile and desktop apps) can't, because anything shipped to a device can be extracted.
What to learn
- Confidential vs public clients, and why a mobile app can't hold a client secret
- The refresh token grant and when an authorization server issues refresh tokens
- The device authorization grant: device code, user code, verification URI and polling
- Why the implicit and password grants are deprecated, and what replaces each
- Token revocation (RFC 7009) and authorization server metadata (RFC 8414)
Free resources
Practice
Write a small command-line tool that logs in with the device authorization grant: request a device code, print the user code and URL, poll the token endpoint (respecting interval and slow_down), and print the user's name from the token once approved. Use a local Keycloak or any provider that supports the grant.
OAuth security best practice and OAuth 2.1
Most OAuth breaches come from small deviations: a redirect URI matched by prefix, a missing state, a token in a URL, or a client that trusts the wrong authorization server. RFC 9700 (the OAuth 2.0 Security Best Current Practice, January 2025) collects the lessons: match redirect URIs exactly, use PKCE for every client, never use the implicit or password grants, don't put tokens in URLs, restrict token audience and privileges, and use sender-constrained or rotating refresh tokens for public clients. With several authorization servers, check the iss parameter on the response (RFC 9207) to stop mix-up attacks.
Newer specs close remaining gaps. Pushed Authorization Requests (PAR, RFC 9126) send the authorization parameters to the server over the back channel first, so they can't be read or tampered with in the browser. DPoP (RFC 9449) binds a token to a key held by the client, so a stolen token is useless without that key; mTLS-bound tokens (RFC 8705) do the same for servers. OAuth 2.1 bundles OAuth 2.0 with these lessons (PKCE required, implicit and password grants removed, exact redirect matching). It is still an IETF Internet-Draft as of November 2026, but you can build to it today, because it only removes risky options.
What to learn
- Exact redirect URI matching and the open-redirect and code-theft attacks it prevents
- CSRF on the callback, and how
state and PKCE stop it
- Mix-up attacks and the
iss response parameter (RFC 9207)
- Pushed Authorization Requests (RFC 9126)
- Sender-constrained tokens: DPoP (RFC 9449) and mTLS-bound tokens
- What OAuth 2.1 changes compared with RFC 6749
Free resources
Practice
Do the free PortSwigger OAuth labs (start with "Authentication bypass via OAuth implicit flow" and "Forced OAuth profile linking"). Then audit the client you built in the PKCE topic against RFC 9700's checklist and write down every rule it already follows and every one it breaks.
Am I ready? Stage 5 quiz
A client app receives an OAuth access token for a user. What does that token prove on its own?
- That the user is logged in to the client app
- That the bearer may call certain APIs with certain scopes
- The user's email address and name
- That the user has already completed MFA
OAuth is for delegated authorization. Proving who logged in is the job of the OpenID Connect ID token.
What does PKCE protect against?
- Users choosing weak passwords
- Tokens expiring too early
- Attackers reading the token endpoint over plain HTTP
- An intercepted authorization code being redeemed by someone else
Only the client that made the code_verifier can redeem the code, because the server checks it against the challenge sent earlier.
A single-page app still uses the implicit grant. What should it switch to?
- The authorization code flow with PKCE
- The resource owner password grant
- The client credentials grant with a secret in the JavaScript
- Nothing: the implicit grant is the recommended flow for SPAs
The implicit grant puts tokens in the URL and is deprecated by RFC 9700 and removed in OAuth 2.1. Code + PKCE replaces it.
An authorization server accepts any redirect URI that starts with https://app.example.com. Why is that dangerous?
- It makes tokens expire immediately
- It disables the consent screen
- A URI like
https://app.example.com.evil.net could receive the code - It forces the client to use the implicit grant
Prefix and pattern matching have leaked codes many times. RFC 9700 requires exact string matching of registered redirect URIs.
Stage 6 · Intermediate OpenID Connect
OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0: the same flows, plus an ID token that tells your app who logged in. It is what "Sign in with…" buttons and most modern single sign-on use.
OIDC basics: ID tokens and claims
Add the openid scope to an authorization code request and the token response contains an extra token: the ID token, a signed JWT written for your app (its aud is your client id). It says who the user is (sub), who vouches for them (iss), when they logged in (auth_time) and often how (amr, acr). The access token is still for calling APIs; never send the ID token to an API as if it were an access token, and never use an access token to decide who logged in.
The extra scopes profile, email, address and phone ask for standard claims such as name, email and email_verified. The key you store for a user is the pair iss + sub: sub is unique and never reassigned within one issuer, while emails change and can be reused. OIDC Core defines the authorization code flow (recommended), plus implicit and hybrid flows you'll mostly see in older systems.
What to learn
- What OIDC adds to OAuth: the
openid scope, the ID token, the UserInfo endpoint
- ID token claims:
iss, sub, aud, exp, iat, auth_time, nonce, acr, amr
- ID token vs access token: who each one is for, and what each one may be used for
- Standard scopes and claims, and why
email_verified matters
- Using
iss + sub as the stable user key, not the email address
Free resources
Practice
Log in to a test app through any OIDC provider with the scopes openid profile email. Decode the ID token and the access token side by side, and list for each: its audience, its lifetime, and the claims it carries. Then explain in two sentences why your API must not accept the ID token.
Discovery, JWKS and validating an ID token
Every OIDC provider publishes a discovery document at {issuer}/.well-known/openid-configuration: a JSON file listing its endpoints, supported scopes, signing algorithms and the jwks_uri where its public signing keys live. Libraries read it so you configure only the issuer URL. The JWKS holds several keys during rotation; the token's kid header says which one signed it, and a good client caches the set and refetches it when it sees an unknown kid.
Validating an ID token is a fixed checklist: verify the signature with a key from the JWKS using an algorithm you expect; check iss matches exactly, aud contains your client id (and azp when there are several audiences), exp is in the future, and nonce equals the value you put in the authorization request. The nonce ties the token to this login attempt and stops replays. Use a certified library for the cryptography; the claim checks below show what it does for you.
{
"issuer": "https://login.example.com",
"authorization_endpoint": "https://login.example.com/authorize",
"token_endpoint": "https://login.example.com/token",
"userinfo_endpoint": "https://login.example.com/userinfo",
"jwks_uri": "https://login.example.com/.well-known/jwks.json",
"end_session_endpoint": "https://login.example.com/logout",
"scopes_supported": ["openid", "profile", "email"],
"id_token_signing_alg_values_supported": ["RS256", "ES256"],
"code_challenge_methods_supported": ["S256"]
}
ISSUER = "https://login.example.com"
CLIENT_ID = "my-web-app"
SKEW = 60 # seconds of clock skew we tolerate
def check_claims(c: dict, nonce: str, now: int) -> str:
# Run AFTER the signature was verified with a key from the JWKS
if c.get("iss") != ISSUER:
return "bad issuer"
aud = c.get("aud")
auds = aud if isinstance(aud, list) else [aud]
if CLIENT_ID not in auds:
return "not for this client"
if len(auds) > 1 and c.get("azp") != CLIENT_ID:
return "bad azp"
if now > c["exp"] + SKEW:
return "expired"
if c.get("nonce") != nonce:
return "nonce mismatch (replay?)"
return "ok, user key = " + c["iss"] + " | " + c["sub"]
claims = {"iss": ISSUER, "sub": "248289761001", "aud": CLIENT_ID,
"exp": 1_800_000_600, "iat": 1_800_000_000, "nonce": "n-0S6_WzA2Mj"}
print(check_claims(claims, "n-0S6_WzA2Mj", now=1_800_000_100))
# prints ok, user key = https://login.example.com | 248289761001
print(check_claims(claims, "other-nonce", now=1_800_000_100))
# prints nonce mismatch (replay?)
print(check_claims(claims, "n-0S6_WzA2Mj", now=1_800_001_000))
# prints expired
What to learn
- The discovery document and the fields your library reads from it
- JWKS,
kid, key rotation and caching the key set safely
- The full ID token validation checklist from OIDC Core section 3.1.3.7
- The
nonce parameter and how it stops token replay
- The UserInfo endpoint and when to call it instead of trusting ID token claims
Free resources
Practice
Fetch the discovery document of two real providers (for example https://accounts.google.com/.well-known/openid-configuration) and of your local Keycloak, then fetch each jwks_uri. Write a small script that validates an ID token from your Keycloak with a maintained JWT library, and make it fail on purpose with a wrong audience, an expired token and a wrong nonce.
Logout in OpenID Connect
Logging out is harder than logging in, because after an OIDC login there are at least two sessions: your app's own session and the user's session at the provider. Clearing only your cookie means the next "Log in" click signs the user straight back in. OIDC defines three logout specs. RP-Initiated Logout: your app redirects the browser to the provider's end_session_endpoint with id_token_hint and a registered post_logout_redirect_uri.
To log the user out of other apps too, the provider must tell them. Front-Channel Logout loads each app's logout URL in hidden iframes, which modern browsers increasingly break because third-party cookies are blocked. Back-Channel Logout sends each app a signed logout token server to server; it is the reliable choice, but your app must be able to find and kill sessions by sid or sub, which means a server-side session store.
What to learn
- Local logout vs provider logout vs logout from every app (single logout)
- RP-Initiated Logout:
end_session_endpoint, id_token_hint, post_logout_redirect_uri
- Front-channel logout and why third-party cookie blocking hurts it
- Back-channel logout tokens, how to validate them, and the
sid claim
- What logout means for access and refresh tokens already issued (revoke them)
Free resources
Practice
Connect two small apps to the same local Keycloak realm. Implement RP-initiated logout in the first and back-channel logout in both, keeping sessions in a server-side store keyed by sid. Log out from app one and prove that app two's session is gone too.
Social login and account linking
"Sign in with Google", "Sign in with Apple" and "Sign in with Microsoft" are OIDC providers: you register an app, get a client id, and run the code flow. Not every "Sign in with" button is OIDC, though: GitHub's user login is plain OAuth 2.0, so there's no ID token and you call its user API with the access token to find out who logged in. Social login removes passwords from your app, but you now depend on the provider being available and on the user keeping that account.
The hard part is account linking. If a user who signed up with a password later clicks "Sign in with Google" using the same email, should that log them in to the same account? Only if the provider says the email is verified and you trust it for that domain; otherwise an attacker who registers your victim's email at a careless provider takes over the account. The safest pattern is to link only after the user has proved control of the existing account (by logging in to it first). Apple can also hide the real email behind a private relay address.
What to learn
- Registering an OIDC client with Google, Apple or Microsoft and the redirect URIs each needs
- Plain OAuth providers (GitHub) vs OIDC providers, and how to identify the user with each
- Storing provider identities in a separate table: user ↔ (issuer, subject)
- Safe account linking:
email_verified, trusted issuers and explicit linking
- Handling relay emails, deleted provider accounts and users with several providers
Free resources
Practice
Add "Sign in with Google" and "Sign in with GitHub" to a small app with an existing email + password login. Store provider identities in their own table, and make linking require a logged-in session. Write a test for the attack: a social login whose unverified email matches an existing user must not log in as that user.
Am I ready? Stage 6 quiz
Which value should you store as the stable key for a user who logs in with OIDC?
- The
email claim - The access token
- The
iss and sub claims together - The
nonce
sub is unique and never reassigned within an issuer. Emails change and can be recycled.
What is the nonce in an OIDC authentication request for?
- Binding the ID token to this login attempt so it can't be replayed
- Choosing the signing algorithm
- Telling the provider which scopes to show
- Encrypting the ID token
The client sends a random nonce and checks the same value comes back inside the ID token.
Your API receives a request with an OIDC ID token as the bearer token. What should it do?
- Accept it if the signature is valid
- Accept it if
email_verified is true - Exchange it for the user's password
- Reject it: ID tokens are for the client app, APIs take access tokens
An ID token's audience is the client app. APIs should accept only access tokens issued for them.
Which logout mechanism keeps working when browsers block third-party cookies?
- Front-channel logout with iframes
- Back-channel logout with a logout token sent server to server
- Deleting the app's cookie only
- Waiting for the ID token to expire
Back-channel logout doesn't depend on the browser at all, but the app needs a server-side session it can find by sid or sub.
Stage 7 · Intermediate → Advanced Single Sign-On
Single sign-on lets people log in once and use many applications. Learn how federation and trust work, how the sessions fit together, how to choose an identity provider, and how SaaS products offer SSO to their business customers.
SSO basics: identity providers, service providers and trust
With single sign-on the applications stop handling credentials. One identity provider (IdP) logs the user in, and each application (called a service provider, SP, in SAML, or a relying party, RP, in OIDC) trusts the IdP's signed statement about who the user is. That trust is set up in advance: the app knows the IdP's issuer and signing keys, and the IdP knows the app's id and where it may send responses. This is federation.
For users SSO means one password (or passkey) and one MFA prompt. For the organisation it means one place to enforce password and MFA rules, see who logged in where, and switch everything off when someone leaves. The flip side: the IdP becomes the most valuable target and a single point of failure, so protect and monitor it accordingly. Today SSO runs on OpenID Connect or SAML 2.0; older systems use Kerberos inside a corporate network (see directories).
What to learn
- IdP, SP and RP, and which side issues and which side trusts the assertion
- Federation: exchanging metadata, keys and redirect URLs to establish trust
- SSO vs "same password everywhere" vs a password manager
- Benefits (central policy, MFA, offboarding) and risks (single point of failure, high-value target)
- The protocols: OIDC, SAML 2.0, and Kerberos inside corporate networks
Free resources
Practice
Draw the trust relationships for a company with ten internal apps and one IdP: which keys and URLs each side must know, and what happens when the IdP rotates its signing key. Then list what an attacker gains by compromising one app versus the IdP.
SSO sessions, re-authentication and single logout
SSO works because the IdP keeps its own session (a cookie on the IdP's domain). When a second app redirects the user there, the IdP sees the session and answers immediately, without asking for a password. Each app then creates its own session. These lifetimes are independent: the IdP session might last 8 hours, an app's session 30 minutes, and a banking app may want a fresh login for every payment.
Apps control this with request parameters. In OIDC, prompt=login forces the user to authenticate again, max_age says how old the login may be (check auth_time in the ID token), and prompt=none asks silently, failing with login_required if there's no IdP session. SAML has ForceAuthn and IsPassive. Single logout (ending every app's session at once) is the part that most often doesn't work fully; see OIDC logout and design for it from the start.
What to learn
- The IdP session vs each application's session, and how their lifetimes interact
- Silent SSO with
prompt=none and how third-party cookie blocking affects iframes
- Forcing re-authentication with
prompt=login, max_age and auth_time
- SAML's
ForceAuthn and IsPassive
- Single logout options and their limits
Free resources
Practice
In a local Keycloak realm, set the SSO session idle timeout to 10 minutes and your app's session to 2 minutes. Log in, wait 3 minutes and see the app re-login silently; wait 11 minutes and see the password prompt. Then add a "confirm payment" button that sends max_age=0 and checks auth_time.
Choosing and running an identity provider
You rarely write an IdP yourself. The options fall into three groups: open-source, self-hosted servers (Keycloak, Zitadel, Authentik, Ory), cloud identity services (Okta, Auth0, Microsoft Entra ID, Amazon Cognito, Google Cloud Identity Platform) and, for workforce identity, whatever the company already uses for email and devices. Compare them on protocols (OIDC, SAML, SCIM), MFA and passkey support, customisable login pages, multi-tenancy, pricing per monthly active user, data residency, and how you get your users out again (password hash export).
Self-hosting gives control and no per-user fees, but you own upgrades, backups, high availability and security patches of a critical system. Whatever you choose, keep your applications protocol-based (standard OIDC libraries, not a vendor SDK everywhere) so you can switch later. Keycloak is the easiest way to learn: it runs in one container and supports everything in this roadmap.
# Throwaway Keycloak for learning (development mode, never production)
docker run --rm -p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:26.8.2 start-dev
# Admin console: http://localhost:8080/admin (create a realm, a client, users)
What to learn
- Self-hosted vs managed IdPs, and what you take on when you self-host
- Comparing providers: protocols, MFA and passkeys, branding, tenants, pricing, export
- Realms or tenants, clients, users, groups, roles and identity brokering
- Custom login pages vs hosted login pages, and why hosted is usually safer
- Avoiding lock-in: standard protocols and migrating users with their password hashes
Free resources
Practice
Run Keycloak locally, create a realm, a confidential client and two users, and turn on TOTP for one of them. Then fill in a one-page comparison of Keycloak and two managed providers for a 10,000-user customer app: cost, MFA and passkeys, hosting effort and how you would export users.
SSO for SaaS products: enterprise customers and multi-tenancy
When you sell software to companies, their IT team will ask for "SSO with our IdP": every customer brings its own Okta, Entra ID or Google Workspace, over SAML or OIDC. Your app becomes a multi-tenant relying party. Each tenant has its own connection (metadata, client id, certificates), and the login page must work out which one to use. That step is home realm discovery: usually from the email domain the user types, sometimes from a tenant-specific URL like acme.yourapp.com.
Accounts are often created on first login, which is just-in-time (JIT) provisioning, with roles mapped from the IdP's groups. Only accept a domain for a tenant after the customer has verified they own it (a DNS TXT record), or one customer could claim another's users. Customers also expect to enforce SSO (no local passwords for their staff) and to deprovision people centrally, which is where SCIM comes in. Identity brokers (Keycloak, Auth0, WorkOS and others) can handle the many connections for you.
What to learn
- Per-tenant SSO connections and storing their configuration safely
- Home realm discovery by email domain or tenant URL
- Verifying domain ownership before routing a domain to a tenant's IdP
- JIT provisioning and mapping IdP groups to your roles
- Enforcing SSO, admin break-glass accounts, and deprovisioning
Free resources
Practice
Extend your app so tenant "acme" logs in through a second Keycloak realm acting as their IdP. Route users by email domain only after a fake DNS-verification step, create accounts on first login, and map an IdP group acme-admins to your app's admin role.
Am I ready? Stage 7 quiz
Why does a user not see a login form when they open a second app connected to the same IdP?
- The two apps share one database of passwords
- The first app sent the password to the second app
- The browser auto-fills the password and submits it
- The IdP still has a session cookie and answers the second app's request at once
The IdP's own session is what makes SSO work. Each app still creates its own session afterwards.
A payment page must be sure the user typed their credentials in the last minute. What should it send in the OIDC request?
prompt=nonemax_age=0 (or prompt=login) and then check auth_timeresponse_type=token- A longer
state value
prompt=none does the opposite: it never shows a login screen. Always check auth_time in the ID token afterwards.
In a multi-tenant SaaS app, what must happen before you route all @acme.com logins to Acme's IdP?
- Acme proves it owns the domain, for example with a DNS TXT record
- Acme sends you its users' passwords
- Acme's IdP switches to the implicit flow
- Nothing: the email domain alone is proof
Without domain verification any tenant could claim another company's domain and capture its users' logins.
What is the main risk of a single identity provider for the whole company?
- Users have to remember more passwords
- MFA can't be enforced centrally
- It becomes a high-value target and a single point of failure
- Offboarding becomes slower
Central login is a big win for security and offboarding, but compromising or losing the IdP affects every app, so it needs the strongest protection and high availability.
Stage 8 · Advanced SAML 2.0
SAML 2.0 is the XML-based SSO standard from 2005 that still runs most enterprise and government single sign-on. You'll meet it as soon as a business customer asks for SSO, so learn how it works, how to read its messages, and the attacks that make it easy to get wrong.
SAML basics: assertions, metadata and bindings
In SAML the IdP sends the service provider a signed XML assertion: who the user is (the Subject with a NameID), how and when they logged in (AuthnStatement), extra facts such as email and groups (AttributeStatement), and the conditions under which the assertion is valid (audience, time window). It travels inside a Response message, and the IdP signs the response, the assertion, or both.
Each side is identified by an entityID (usually a URL) and describes itself in a metadata XML file: its signing certificate, its endpoints and supported bindings. The SP's most important endpoint is the Assertion Consumer Service (ACS) URL, where responses arrive. Bindings say how messages travel: HTTP-Redirect (compressed and encoded in the URL, used for small requests), HTTP-POST (an auto-submitting HTML form, used for responses because they are large) and HTTP-Artifact (a reference fetched over the back channel). Setting up SAML mostly means exchanging metadata between the two sides.
What to learn
- Assertions: Subject, NameID formats, AuthnStatement, AttributeStatement, Conditions
- Requests and responses:
AuthnRequest, Response, Status
- entityID, ACS URL and the metadata file each side publishes
- The HTTP-Redirect, HTTP-POST and HTTP-Artifact bindings
- Signing certificates in metadata and how certificate rollover works
Free resources
Practice
Download the SAML metadata of a local Keycloak realm (/realms/<realm>/protocol/saml/descriptor) and label every element: entityID, signing certificate, SSO endpoints and their bindings. Decode the certificate and note its expiry date.
SAML flows: SP-initiated, IdP-initiated and RelayState
In the SP-initiated flow the user starts at your app: it sends an AuthnRequest to the IdP (usually by redirect), the user logs in, and the IdP POSTs a signed Response to your ACS URL. Your app checks that the response answers a request it actually made (InResponseTo matches the request's ID). RelayState is an opaque value that comes back unchanged, typically the page to return to; validate it like any redirect target, or it becomes an open redirect.
In the IdP-initiated flow the user clicks a tile in the company's app portal and the IdP posts a response nobody asked for. It's convenient, but there's no request to match, so a stolen or injected response is harder to detect. Support it only if customers need it, with short assertion lifetimes and replay detection, or turn it into an SP-initiated flow by redirecting back through your own login.
Browser Service provider (app) Identity provider
| 1. GET /dashboard | |
|------------------------->| no session |
| 2. 302 to IdP SSO URL ?SAMLRequest=...&RelayState=... |
|--------------------------------------------------------->|
| | 3. user logs in (+ MFA) |
| 4. HTML form auto-POSTs SAMLResponse + RelayState |
|<---------------------------------------------------------|
| 5. POST /saml/acs | |
|------------------------->| 6. verify signature, issuer, |
| | audience, InResponseTo, |
| | time window, not replayed |
| 7. session cookie + 302 to RelayState page |
|<-------------------------| |
<!-- A trimmed SAML Response (signature and namespaces left out) -->
<samlp:Response ID="_r1" InResponseTo="_req42"
Destination="https://app.example.com/saml/acs">
<saml:Issuer>https://idp.example.org</saml:Issuer>
<samlp:Status><samlp:StatusCode Value="...:Success"/></samlp:Status>
<saml:Assertion ID="_a1" IssueInstant="2026-11-06T10:00:00Z">
<saml:Issuer>https://idp.example.org</saml:Issuer>
<ds:Signature>...covers #_a1...</ds:Signature>
<saml:Subject>
<saml:NameID>ana@example.org</saml:NameID>
<saml:SubjectConfirmation Method="...:bearer">
<saml:SubjectConfirmationData InResponseTo="_req42"
Recipient="https://app.example.com/saml/acs"
NotOnOrAfter="2026-11-06T10:05:00Z"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2026-11-06T09:59:30Z"
NotOnOrAfter="2026-11-06T10:05:00Z">
<saml:AudienceRestriction>
<saml:Audience>https://app.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AttributeStatement>...email, groups...</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
What to learn
- The SP-initiated flow, step by step, and matching
InResponseTo to the request ID
- The IdP-initiated flow and why it is riskier
- RelayState and validating where you redirect afterwards
- Reading a decoded
SAMLRequest and SAMLResponse with a browser extension
- Mapping attributes (email, groups) to your user and role model
Free resources
Practice
Connect a small app to a local Keycloak realm over SAML with a maintained library for your language. Capture one login with your browser's DevTools, decode the SAMLResponse and find the issuer, NameID, audience, time window and InResponseTo. Then try IdP-initiated login and note which checks your library can no longer do.
SAML security: signatures, wrapping attacks and replay
SAML's security rests on XML signatures, which are notoriously hard to verify correctly. In an XML signature wrapping (XSW) attack, the attacker keeps a validly signed element in the document but adds a second, unsigned assertion where the application looks for the user. The signature check passes on one element while the app reads another. The fix is to read data only from the exact element the signature covers, and to reject responses with unexpected structure. Other classic bugs: accepting unsigned assertions, trusting the certificate embedded in the message instead of the one from metadata, and comment-injection tricks that truncate the NameID.
After the signature, check the rest: the Issuer is the IdP you expect, the Audience is your entityID, the Recipient and Destination are your ACS URL, the time window is current (allow a small clock skew), InResponseTo matches, and the assertion ID hasn't been seen before (replay cache). Because SAML is XML, disable external entities to avoid XXE. Never write your own SAML parser: use a maintained library and keep it updated, since serious signature bypasses keep being found in popular ones.
What to learn
- How XML signatures and canonicalisation work, at a high level
- XML signature wrapping attacks and why "signature valid" isn't enough
- Using only the IdP certificate from metadata, never one embedded in the message
- Issuer, Audience, Recipient, Destination, time window and
InResponseTo checks
- Replay protection with an assertion ID cache, and XXE-safe XML parsing
Free resources
Practice
Using the SAML app from the previous topic, write tests that tamper with a captured response: remove the signature, change the NameID, change the audience, replay the same response twice, and send it after NotOnOrAfter. Every test must be rejected; record which check stopped each one.
SAML vs OpenID Connect, and bridging the two
Both give you browser SSO; they differ in age and reach. SAML is XML with signatures, built for browser redirects and POSTs between enterprise web apps; it has no standard way for mobile apps or APIs to use the result. OIDC is JSON and JWTs on top of OAuth, so the same login also gives you access tokens for APIs, and it suits SPAs, mobile apps and modern libraries. For new systems choose OIDC; add SAML when customers or government federations require it.
You don't have to support both in every application. An identity broker (Keycloak, or a managed provider) can accept SAML from a customer's IdP and speak OIDC to your apps, so your code has one protocol and one set of libraries. The same broker can switch a customer from SAML to OIDC later without touching your apps.
What to learn
- Format and transport differences: XML signatures vs JWTs, POST forms vs redirects + back channel
- What each one offers mobile apps, SPAs and APIs
- Where each is required: enterprise apps, education and government federations
- Identity brokering: SAML in, OIDC out
Free resources
Practice
In Keycloak, add a second realm as a SAML identity provider to your main realm, so users log in to your OIDC app through SAML without any change to the app. Write down which attributes you had to map and how.
Am I ready? Stage 8 quiz
Which SAML binding is normally used to deliver the IdP's Response to the service provider?
- HTTP-Redirect in the URL
- HTTP-POST through an auto-submitting HTML form
- An email to the user
- A WebSocket message
Signed responses are too large for a URL, so the IdP returns an HTML form that the browser POSTs to the ACS URL.
A SAML library confirms "signature valid" but the app reads the user from a different, unsigned assertion in the same document. What is this attack called?
- Cross-site scripting
- Credential stuffing
- XML signature wrapping
- Session fixation
The app must use only the element the signature actually covers and reject unexpected document structure.
Which certificate should the service provider use to verify a SAML response?
- The one embedded in the response's
KeyInfo - Any certificate signed by a public CA
- The SP's own TLS certificate
- The IdP certificate from metadata configured in advance
Trusting a certificate sent inside the message lets an attacker sign their own assertion. Trust comes from metadata exchanged beforehand.
Why is IdP-initiated SSO considered riskier than SP-initiated SSO?
- There is no request to match, so
InResponseTo can't be checked - It doesn't support signatures
- It always uses plain HTTP
- It can't carry attributes such as email
An unsolicited response can't be tied to a login the user started, which makes stolen or injected responses harder to detect.
Stage 9 · Intermediate MFA and OTP
A stolen password should not be enough to get in. Learn how second factors work, which ones stop phishing and which only slow attackers down, and how to handle the hard parts: enrolment, lost devices and asking for more proof only when it matters.
MFA basics: factors, assurance levels and phishing resistance
Multi-factor authentication (MFA) asks for proof from two or more different factor types: something you know (a password or PIN), something you have (a phone, a security key, a passkey on a device) and something you are (a fingerprint or face, used to unlock a device). Two passwords are still one factor. MFA blocks most attacks that rely on a leaked or guessed password, which is why it is the single most valuable control you can add to a login.
Not all second factors are equal. A code you type (SMS, email, an authenticator app) can be phished: a fake site asks for it and relays it to the real one within seconds. NIST SP 800-63B-4 says authenticators that rely on manually entering an output are not phishing-resistant; only cryptographic authenticators bound to the site, such as FIDO2 security keys and passkeys, are. At AAL2 verifiers must offer at least one phishing-resistant option, and AAL3 requires one with a non-exportable key. A practical order of preference: passkeys or security keys, then an authenticator app or push with number matching, then SMS only as a fallback.
What to learn
- The three factor types, and why a password plus a security question is still single-factor
- AAL1, AAL2 and AAL3 in NIST SP 800-63B-4 and what each one requires
- Phishing-resistant vs phishable factors, and why typed codes can be relayed by a fake site
- Enrolment: proving it is really the account owner before adding or removing a factor
- Rate-limiting failed second-factor attempts and alerting the user when a factor changes
Free resources
Practice
Turn on MFA for your own email, code host and cloud accounts, using a passkey or security key where offered. For each one, write down which factors it allows, whether any of them is phishing-resistant, and what the recovery path is if you lose your phone.
TOTP and HOTP: authenticator app codes
Authenticator apps implement two short RFCs. HOTP (RFC 4226) computes HMAC-SHA1 over a shared secret and a counter, then "dynamically truncates" the result to 6 or 8 digits. TOTP (RFC 6238) is HOTP where the counter is the current Unix time divided by a time step, usually 30 seconds. Server and app share the secret once, usually through a QR code holding an otpauth://totp/…?secret=BASE32&issuer=… URI, and from then on both compute the same code without talking to each other.
The server side has a few rules that are easy to get wrong: store the secret encrypted (it is a shared secret, so it can't be hashed like a password), accept a small window of one step either way for clock drift, accept each code only once (remember the last used time step), compare in constant time, and rate-limit attempts, because six digits is only a million possibilities. The example reproduces the RFC test vectors with the standard library only.
import base64, hashlib, hmac, struct
def hotp(key: bytes, counter: int, digits: int = 6) -> str:
msg = struct.pack(">Q", counter) # 8-byte big-endian counter
mac = hmac.new(key, msg, hashlib.sha1).digest()
offset = mac[-1] & 0x0F # dynamic truncation
code = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(code % 10 ** digits).zfill(digits)
def totp(key: bytes, unix_time: int, step: int = 30, digits: int = 6):
return hotp(key, unix_time // step, digits) # counter = time step
def verify(key: bytes, code: str, now: int, window: int = 1) -> bool:
# accept one step either side for clock drift; constant-time compare
return any(hmac.compare_digest(totp(key, now + i * 30), code)
for i in range(-window, window + 1))
key = b"12345678901234567890" # RFC 4226 / 6238 test key
print(hotp(key, 0)) # prints 755224
print(totp(key, 59, digits=8)) # prints 94287082
print(totp(key, 1111111109, digits=8)) # prints 07081804
print(verify(key, totp(key, 1000), now=1030)) # prints True
print(verify(key, totp(key, 1000), now=1100)) # prints False
print(base64.b32encode(key).decode()) # prints GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
What to learn
- HMAC over a counter, dynamic truncation, and how HOTP becomes TOTP
- The
otpauth:// URI format, Base32 secrets and showing it as a QR code
- Clock-drift windows, single use of each code, and rate limits on attempts
- Storing TOTP secrets encrypted, and confirming enrolment with a first valid code
- Why TOTP stops password reuse attacks but not a real-time phishing proxy
Free resources
Practice
Run the example, then extend it into an enrolment flow: generate a random 20-byte secret with secrets.token_bytes, build the otpauth:// URI, turn it into a QR code, scan it with an authenticator app and check that your verify accepts the app's code. Add replay protection so the same code can't be used twice.
SMS, email codes and magic links
Codes sent by SMS or voice call are easy for users but the weakest second factor: attackers take over phone numbers with SIM swaps and number porting, intercept messages through the phone network, or simply phish the code. NIST SP 800-63B-4 still lists the phone network (PSTN) as its one restricted authenticator: allowed, but services should offer alternatives and watch for signs such as a recent SIM change. Treat SMS as better than nothing, not as strong MFA.
Email codes and magic links prove control of a mailbox. NIST does not accept email as an out-of-band authenticator, but email verification and passwordless sign-in links are common for low-risk apps. Done safely, a code or link is random, single-use, short-lived (minutes), tied to the browser session that asked for it, and rate-limited. Use the autocomplete="one-time-code" attribute and the origin-bound SMS format so browsers can fill codes safely.
What to learn
- SIM swap, number porting and SMS interception, and why SMS is a "restricted" authenticator
- Random, single-use, short-lived codes, limited attempts and resend throttling
- Magic links: one-time tokens, short expiry, and stopping link scanners from using them up
- The
one-time-code autocomplete value and the origin-bound SMS message format
- SMS pumping fraud (bots triggering paid texts) and how to cap it
Free resources
Practice
Build an email-code sign-in for a toy app: generate a 6-digit code with a secure random generator, store only its hash with a 10-minute expiry and an attempt counter, allow 5 tries, and make the code unusable after one success. Log every send so you can spot someone requesting codes in a loop.
Push MFA, MFA fatigue and number matching
Push MFA sends an "Is this you signing in?" prompt to an app on the user's phone. It is convenient, but attackers who already have the password can send prompt after prompt, often late at night, until a tired user taps Approve. This is MFA fatigue (or "MFA bombing"; MITRE ATT&CK T1621), and it has been used in real breaches.
The fix is to make approval require context the attacker can't fake. Number matching shows a number on the sign-in screen that the user must type into the app, so a prompt the user didn't start can't be approved by reflex. Also show the app name and location, limit how many prompts can be sent, let users report a prompt as fraud, and alert the security team when many are denied. Number matching still isn't phishing-resistant: a phishing site can show the user the real number.
What to learn
- How push approval works, and how MFA fatigue and push bombing abuse it
- Number matching and showing context (app, location, device) in the prompt
- Rate-limiting prompts, a "this wasn't me" button, and alerting on denials
- Why push with number matching is better than plain push but still phishable
Free resources
Practice
Design the push-approval screen and server rules for a company app: what the prompt shows, how many prompts per 10 minutes are allowed, what happens after three denials, and which alert the security team gets. Then explain in two sentences how a phishing site could still get through.
Recovery codes and step-up authentication
Every MFA system needs a plan for a lost phone. Recovery codes are one-time secrets (NIST calls them look-up secrets) shown once at enrolment: generate around ten with a secure random generator, store only their hashes, mark each used, and let users regenerate them. Encourage a second factor (two passkeys, or a passkey plus an app) so recovery is rare. Account recovery is where attackers aim once MFA is on, so a "forgot my second factor" path must be at least as strong as the login it bypasses, and should notify the user and often add a delay.
Step-up authentication asks for stronger or fresher proof only for risky actions: changing the email or password, adding a payee, viewing secrets. In OpenID Connect the app asks for it with the acr_values or max_age parameters and checks the acr, amr and auth_time claims in the ID token. RFC 9470 standardises how an API tells a client "this token isn't strong enough": a 401 with error="insufficient_user_authentication".
What to learn
- Generating, hashing, using and regenerating recovery codes
- Safe recovery when all factors are lost: delays, notifications and identity checks
- Step-up for sensitive actions, and "recent authentication" checks with
auth_time
- The
acr, amr and auth_time claims and the acr_values / max_age parameters
- The RFC 9470
insufficient_user_authentication challenge
Free resources
Practice
Add recovery codes to the TOTP app from the TOTP topic: show ten codes once, store their hashes, and accept each only once. Then protect a "change email" endpoint with step-up: if the user's last authentication is older than 5 minutes, return 401 and make them confirm with their second factor first.
Am I ready? Stage 9 quiz
Why is a TOTP code from an authenticator app not phishing-resistant?
- The shared secret is sent to the server on every login
- Six digits are too short to be secure at all
- A fake site can ask for the code and relay it to the real site in time
- Authenticator apps upload codes to the cloud
Any code the user types can be replayed by a real-time proxy. Phishing resistance needs a cryptographic factor bound to the site's origin, such as a passkey.
In TOTP, what is used as the HOTP counter?
- The current Unix time divided by the time step (usually 30 seconds)
- The number of times the user has logged in
- A random number sent by the server with each login
- The last six digits of the user's phone number
RFC 6238 defines TOTP as HOTP with a time-based counter, so server and app agree on the code without talking to each other.
Attackers with a stolen password keep sending push prompts until the user taps Approve. What helps most?
- Sending the prompts by SMS instead
- Making the push notification louder
- Removing the Deny button
- Number matching, plus a limit on how many prompts can be sent
Number matching means the user must type a number shown on the sign-in screen, which they won't have for a login they didn't start. Limits and alerts stop the bombing.
A user wants to change their account email. Their session started 3 hours ago. What is step-up authentication?
- Logging them out of every device first
- Asking them to prove it's them again (for example with their second factor) before the change
- Raising their role to admin for one request
- Emailing support to approve the change manually
Sensitive actions ask for fresh or stronger proof. The app checks auth_time or acr and re-authenticates if they aren't good enough.
Stage 10 · Intermediate → Advanced Passkeys and WebAuthn
Passkeys replace passwords with public-key cryptography that the browser ties to your domain, so there is nothing to phish, reuse or leak from your database. Learn how WebAuthn works underneath, then how to roll passkeys out to real users.
WebAuthn basics: public keys bound to your site
WebAuthn (a W3C standard, part of FIDO2 together with the CTAP protocol for external keys) lets a website create and use public-key credentials. On registration an authenticator (the phone or laptop's platform authenticator, a password manager, or a USB/NFC security key) makes a new key pair just for your site and gives the server only the public key. On sign-in the server sends a random challenge, the authenticator signs it with the private key after the user unlocks it (fingerprint, face or PIN: user verification), and the server checks the signature.
Two properties make this much stronger than passwords and codes. The server stores nothing secret, so a database leak gives attackers nothing to log in with. And every credential is scoped to a relying party ID (your domain): the browser itself puts the real origin into the signed data and refuses to use a credential on another domain, so a look-alike phishing site simply can't ask for it. That is what "phishing-resistant" means.
What to learn
- Relying party, authenticator, client (browser) and the RP ID
- Platform authenticators vs roaming security keys, and where FIDO2 and CTAP fit
- User presence vs user verification (a tap vs a biometric or PIN)
- Why origin binding makes WebAuthn phishing-resistant and why a server leak is harmless
- Discoverable credentials (resident keys), which allow sign-in without typing a username
Free resources
Practice
Register and sign in on the webauthn.io demo with your phone or laptop, and with a security key if you have one. Open DevTools and use the WebAuthn panel (Chrome: More tools → WebAuthn) to add a virtual authenticator, then watch the credential it creates.
Registration and authentication ceremonies
WebAuthn calls its two flows ceremonies. In registration the server sends options (a random challenge, the RP ID and name, a user handle, allowed algorithms such as ES256 and RS256), the page calls navigator.credentials.create(), and the server verifies the response and stores the credential ID, public key and signature counter against the user. In authentication the server sends a new challenge, the page calls navigator.credentials.get(), and the server checks the signature with the stored public key.
// Sign in: options come from your server (challenge is single-use)
const options = await (await fetch("/webauthn/login/options")).json();
const cred = await navigator.credentials.get({
publicKey: {
challenge: base64urlToBytes(options.challenge),
rpId: "shop.example",
userVerification: "preferred",
allowCredentials: [], // empty: let the user pick a passkey
},
});
// Send cred.response (clientDataJSON, authenticatorData, signature,
// userHandle) to the server, which verifies everything below.
Server verification is a checklist: the challenge matches the one you issued (and is used once), type is webauthn.create or webauthn.get, the origin is yours, the first 32 bytes of the authenticator data equal SHA-256 of your RP ID, the user-present and (if you required it) user-verified flags are set, and the signature is valid. Use a maintained library for the CBOR and signature parts; the example below shows the checks that stop replay and phishing.
import base64, hashlib, hmac, json
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
# Saved by the server when it started the ceremony (random in real life)
expected_challenge = b64url(b"server-random-challenge-0001")
expected_origin = "https://shop.example"
rp_id = "shop.example"
# clientDataJSON as the browser builds it (sent base64url-encoded)
client_data = json.dumps({
"type": "webauthn.get",
"challenge": expected_challenge,
"origin": "https://shop.example",
}).encode()
def check_client_data(raw: bytes) -> list[str]:
c = json.loads(raw)
problems = []
if c["type"] != "webauthn.get":
problems.append("wrong ceremony type")
if not hmac.compare_digest(c["challenge"], expected_challenge):
problems.append("challenge mismatch (replay?)")
if c["origin"] != expected_origin:
problems.append("origin mismatch (phishing?)")
return problems
print(check_client_data(client_data)) # prints []
phish = client_data.replace(b"shop.example", b"shop-example.co")
print(check_client_data(phish)) # prints ['origin mismatch (phishing?)']
# authenticatorData starts with SHA-256(rp_id): the first 32 bytes
print(hashlib.sha256(rp_id.encode()).hexdigest()[:16])
# prints 0f59463c606c5b0e
What to learn
- Registration options: challenge,
rp, user.id, pubKeyCredParams, excludeCredentials
- Authentication options: challenge,
rpId, allowCredentials, userVerification
- clientDataJSON, authenticatorData and its flags, and the signature over both
- Storing credential ID, public key, sign count and transports per user (users may have several)
- Server-side verification with a library, and why the challenge must be random and single-use
Free resources
Practice
Build passkey sign-up and sign-in for a small app with a server library (SimpleWebAuthn for Node, py_webauthn for Python, or Spring Security). Test it with a DevTools virtual authenticator, then try to replay a captured sign-in response and confirm the server rejects it.
Passkeys: synced, device-bound and autofill sign-in
A passkey is a FIDO/WebAuthn discoverable credential that users can use instead of a password. Synced passkeys are backed up by a passkey provider (the platform's password manager or a third-party one) and appear on all the user's devices, which solves the "lost my phone" problem; device-bound passkeys never leave one authenticator, such as a security key. NIST SP 800-63B-4 accepts syncable authenticators up to AAL2 but not AAL3, because the key can be exported to the sync service.
Good passkey UX matters as much as the crypto. Conditional UI shows saved passkeys in the username field's autofill list: add autocomplete="username webauthn" to the input and call navigator.credentials.get() with mediation: "conditional" when the page loads. Cross-device sign-in lets a user scan a QR code with their phone to sign in on another computer, with Bluetooth proving the phone is nearby. Related Origin Requests let one passkey work across a few of your own domains (for example country sites) via a JSON file at /.well-known/webauthn.
What to learn
- Synced vs device-bound passkeys, and the backup-eligible and backed-up flags
- Conditional UI (autofill) with
mediation: "conditional" and the webauthn autocomplete token
- Cross-device (hybrid) sign-in with a phone and QR code
- Related Origin Requests and the
/.well-known/webauthn file
- Why NIST allows synced passkeys at AAL2 but requires non-exportable keys at AAL3
Free resources
Practice
Add conditional UI to your sign-in form from the previous topic so saved passkeys appear in autofill. Sign in from a second computer with the cross-device QR flow, and record which flags (backup eligible, backed up, user verified) each of your authenticators reports.
Rolling out passkeys: UX, fallbacks and recovery
Most sites add passkeys next to passwords first. Offer to create one right after a successful sign-in or in account settings, let users name and delete them, and allow several per account. Keep a fallback (password plus MFA, or an email code) while adoption grows, and remember the account is only as strong as its weakest way in: once most users have passkeys, consider removing passwords for those accounts. Recovery needs the same care as with MFA: a second passkey, a recovery code, or a careful identity check.
Keep the server and the user's passkey manager in sync. When a user deletes a passkey or changes their name, the WebAuthn Signal API (PublicKeyCredential.signalUnknownCredential(), signalAllAcceptedCredentials(), signalCurrentUserDetails()) tells the provider so stale passkeys stop appearing. Attestation (proof of the authenticator's make and model) is usually unnecessary for consumer sites; ask for it only when policy requires specific certified hardware, as in some enterprises. Use a maintained server library rather than parsing CBOR yourself.
What to learn
- Where to prompt for passkey creation, and letting users manage several passkeys
- Fallback sign-in methods during the transition, and when to retire passwords
- Account recovery without undoing the security passkeys give you
- The Signal API for keeping passkey providers in sync with your server
- Attestation: what it proves and when it's worth requiring
- Choosing and keeping up to date a server-side WebAuthn library
Free resources
Practice
Write a one-page passkey rollout plan for an app with password + TOTP today: where users are offered a passkey, how many they can have, what the fallback is, how a user who lost every device gets back in, and which number (share of sign-ins by passkey) you'll track to decide when to drop passwords.
Am I ready? Stage 10 quiz
What does a WebAuthn server store for each passkey?
- The user's fingerprint template
- The credential ID and the public key (plus a signature counter)
- The private key, encrypted with the user's password
- A hash of the user's device PIN
Only the public key leaves the authenticator. Biometrics and PINs stay on the device and only unlock the private key.
Why can't a phishing site at shop-example.co use a passkey created for shop.example?
- Passkeys expire after every sign-in
- The phishing site doesn't know the user's password
- The user's phone blocks unknown websites
- The browser only offers a credential to its own RP ID and signs the real origin into the response
Origin binding is enforced by the browser, not by the user noticing the URL. That is why passkeys are phishing-resistant.
How do you show saved passkeys in the username field's autofill list?
- Call
navigator.credentials.get() with mediation: "conditional" and add webauthn to the input's autocomplete - Store the passkeys in localStorage and render them in a dropdown
- Ask the user to type their passkey into the password field
- Send the passkey list to the browser in a cookie
That is conditional UI: the request waits silently until the user picks a passkey from autofill.
Under NIST SP 800-63B-4, what is the highest assurance level a synced passkey can meet?
- AAL1 only, because it is synced
- None, synced passkeys aren't accepted
- AAL2
- AAL3
Syncing makes the private key exportable, and AAL3 needs a non-exportable key, so synced passkeys go up to AAL2.
Stage 11 · Intermediate → Advanced Authorization: RBAC and ABAC
Authentication says who someone is; authorization decides what they may do. Broken access control is the most common serious web vulnerability, so learn the models (roles, attributes, relationships), where to put the checks, and how to test them.
Authorization models and architecture
Every authorization decision answers one question: may this subject perform this action on this resource, in this context? The models differ in what they look at. An ACL (access control list) stores who may do what on each resource. RBAC grants permissions to roles and roles to users. ABAC evaluates rules over attributes of the user, resource and environment. ReBAC follows relationships ("Ana is an editor of a folder that contains this doc"). Real systems usually combine them.
The standard architecture splits the job into parts: the policy enforcement point (PEP) is the code that intercepts a request and blocks or allows it, the policy decision point (PDP) evaluates the rules, and policy information points (PIP) supply extra attributes. In a small app all three can be one function; in a large one the PDP may be a separate service or library shared by many APIs. Whatever the size, deny by default and check on the server for every request.
What to learn
- Authentication vs authorization, and why a valid login proves nothing about permissions
- ACL, RBAC, ABAC and ReBAC, with an example where each fits best
- PEP, PDP and PIP, and centralised vs embedded decisions
- Deny by default, least privilege and separation of duties
- Coarse checks (can call this API) vs fine-grained checks (can edit this record)
Free resources
Practice
Take an app you know (a project tracker or a blog) and write its permission matrix: rows are roles or user types, columns are actions on each resource. Mark which cells depend on ownership or other attributes; those are the ones plain RBAC won't express.
Role-based access control (RBAC)
In RBAC you define permissions (such as invoice:approve), group them into roles (such as accountant), and assign roles to users or groups. Code checks permissions, not role names, so adding a role never means changing code. The NIST RBAC model adds role hierarchies (an admin inherits everything an editor has) and constraints such as separation of duties (the person who creates a payment can't approve it).
RBAC is simple to audit and explain, which is why Kubernetes, cloud consoles and most business apps use it. Its weakness is role explosion: when access depends on context (own department, own region, only during an incident), teams invent roles like editor-finance-eu until nobody understands them. When that happens, keep roles coarse and add attribute or relationship rules for the details. Roles usually reach your app as a claim in the token (roles or groups) or from your own database.
What to learn
- Users, roles, permissions and the many-to-many links between them
- Checking permissions in code instead of hard-coding role names
- Role hierarchies and static or dynamic separation of duties
- Role explosion and how to avoid it
- Getting roles from token claims or groups vs from your own database, and keeping them fresh
Free resources
Practice
Design the tables for RBAC (users, roles, permissions, user_roles, role_permissions) and write the one SQL query that answers "does user X have permission Y?". Then compare it with how Kubernetes RBAC expresses Roles and RoleBindings.
Attribute-based access control (ABAC) and policy engines
ABAC decides with rules over attributes: of the subject (department, clearance, tenant), the resource (owner, classification, region), the action, and the environment (time, IP, device posture). One rule like "users may edit documents in their own department" replaces dozens of roles. Cloud IAM uses this idea with tags, for example AWS ABAC matching a principal's tag to a resource's tag.
As rules grow, move them out of scattered if statements into a policy engine and treat them as code: versioned, reviewed and unit-tested. Open Policy Agent (OPA, a graduated CNCF project) uses the Rego language and is common for APIs, Kubernetes admission and CI. Cedar, open-sourced by AWS and used by Amazon Verified Permissions, is designed for application permissions and can be analysed automatically. The example combines RBAC, an ABAC rule, ownership and tenant isolation in plain Python, which is how most apps start.
from dataclasses import dataclass
ROLE_PERMISSIONS = { # RBAC: role -> permissions
"viewer": {"doc:read"},
"editor": {"doc:read", "doc:edit"},
"admin": {"doc:read", "doc:edit", "doc:delete"},
}
@dataclass
class User:
id: str
roles: set[str]
tenant: str
department: str
@dataclass
class Doc:
owner: str
tenant: str
department: str
classified: bool
def rbac_allows(user: User, permission: str) -> bool:
return any(permission in ROLE_PERMISSIONS.get(r, set())
for r in user.roles)
def can(user: User, action: str, doc: Doc) -> bool:
if user.tenant != doc.tenant: # tenant isolation first
return False
if not rbac_allows(user, f"doc:{action}"):
return False # deny by default
if doc.classified and user.department != doc.department:
return False # ABAC: attribute rule
if action == "delete": # ownership rule
return doc.owner == user.id
return True
ana = User("ana", {"editor"}, "acme", "finance")
raj = User("raj", {"admin"}, "acme", "sales")
eve = User("eve", {"admin"}, "other", "finance")
budget = Doc(owner="raj", tenant="acme", department="finance",
classified=True)
print(can(ana, "edit", budget)) # prints True
print(can(ana, "delete", budget)) # prints False
print(can(raj, "read", budget)) # prints False
print(can(eve, "read", budget)) # prints False
What to learn
- Subject, resource, action and environment attributes, and where each comes from
- Writing rules that replace role explosion, and combining RBAC with ABAC
- Policy as code: OPA/Rego or Cedar, with tests and code review for policies
- Tag-based access in cloud IAM, and the risk of users who can change their own tags
- Performance: fetching attributes, caching decisions, and keeping decisions explainable
Free resources
Practice
Run the example and add a rule: contractors may only read documents, and only during working hours. Then write the same policy in Rego in the OPA playground (play.openpolicyagent.org) with a unit test for each rule, and compare which version is easier to review.
Relationship-based access control (ReBAC) and Zanzibar
In apps like Google Docs, access comes from relationships: you can view a file because you're in a group that's a viewer of the folder it's in. ReBAC stores these relationships as tuples (document:plan#viewer@group:eng#member) and answers "can user X view document Y?" by walking the graph. Google described its global system for this, Zanzibar, in a 2019 paper, and several open-source systems follow its model.
OpenFGA (a CNCF project) and SpiceDB let you write an authorization model (types, relations and how they inherit), store relationship tuples, and query "check", "list objects" and "list users". They shine for sharing, nested folders, organisations and teams. The hard parts are keeping tuples in sync with your main database and handling consistency, which Zanzibar solves with "zookies" (consistency tokens) and SpiceDB exposes as ZedTokens.
What to learn
- Relationship tuples, the authorization model, and computed relations such as editor implies viewer
- Check, list-objects and list-users queries, and why list queries are hard in RBAC
- Keeping relationship data in sync with your application database
- The "new enemy" problem and consistency tokens
Free resources
Practice
Model a small Google-Drive-like app in OpenFGA: users, groups, folders and documents, where folder viewers can view the documents inside. Write tuples for three users and run checks that prove a user outside the group can't see a nested document.
Enforcing authorization: IDOR, scopes and tenants
Most access-control bugs aren't in the model, they're a missing check. IDOR (insecure direct object reference), called BOLA in the OWASP API Security Top 10 (API1:2023), happens when GET /api/invoices/1043 returns invoice 1043 to anyone who is logged in. The fix is to check the object, not just the endpoint: load it with the user's tenant and ownership in the query, and return 404 or 403 when it isn't theirs. Hiding a button in the UI or using unguessable IDs doesn't count as a check.
Keep two ideas apart. OAuth scopes limit what a client app may do on the user's behalf (invoices.read); they are not the user's permissions, so an API still checks that this user may read this invoice. In multi-tenant apps, every query must be scoped to the tenant from the token, never from a request parameter. Put checks in one place (middleware, a policy function, method security) and write tests where user A tries to read, change and delete user B's data.
What to learn
- IDOR / BOLA, function-level access control, and mass assignment of fields like
role
- Checking ownership and tenant in the data query, not only at the route
- Scopes (what the client may do) vs permissions (what the user may do)
- Tenant isolation: tenant from the token, row-level security as a safety net
- Automated authorization tests with two users and two tenants
Free resources
Practice
Do the access-control labs in the Web Security roadmap. Then, in your own API, create two users in two tenants and write a test for every endpoint that has an ID in the path, proving user A gets 404 or 403 for user B's objects.
Am I ready? Stage 11 quiz
A logged-in user changes /api/orders/1001 to /api/orders/1002 and sees someone else's order. What is this?
- Cross-site request forgery
- Session fixation
- Credential stuffing
- IDOR, also called broken object level authorization (BOLA)
The endpoint checked that the user was logged in but not that the object belonged to them. Check ownership on every object access.
Your app has roles like editor-finance-eu and editor-sales-us multiplying every month. What usually helps?
- Keep a few coarse roles and add attribute rules (department, region)
- Give everyone the admin role
- Create a new role for each user
- Move the role checks into the frontend
That is role explosion. ABAC rules over attributes express "own department" once instead of one role per combination.
An access token has the scope invoices.read. What does that mean for your API?
- The user may read every invoice in the system
- The token is an admin token
- The client app may read invoices on the user's behalf, but the API must still check which invoices this user may see
- No further checks are needed
Scopes limit the client, not the user. Object-level permission checks still apply.
In the PEP/PDP architecture, what does the policy decision point do?
- Blocks network traffic at the firewall
- Evaluates the policy and returns allow or deny
- Stores user passwords
- Issues access tokens
The enforcement point (PEP) intercepts the request and asks the decision point (PDP), which evaluates the rules with attributes from information points (PIPs).
Stage 12 · Advanced Machine-to-machine authentication
Services, jobs, pipelines and devices need identities too, and there is no human to type a code. Learn how machines get short-lived tokens, how certificates prove identity on both ends of a connection, and how to stop shipping long-lived secrets.
The client credentials grant
When a service calls an API on its own behalf (a nightly billing job calling the invoices API), there is no user to redirect. The OAuth client credentials grant lets the service authenticate to the authorization server as itself and get an access token for specific scopes and an audience. The API then validates that token exactly as it would any other.
POST /oauth2/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&scope=invoices.read
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6ImsxIn0...
How the client proves itself matters. A client secret (sent with HTTP Basic or in the body) is simple but is a shared secret that can leak from config. private_key_jwt (RFC 7523) is stronger: the client signs a short-lived JWT with its private key and the server only holds the public key. Even better are mutual TLS and workload identity, which remove stored secrets altogether. Clients should cache the token until shortly before it expires instead of fetching one per request; there is no refresh token in this grant.
What to learn
- When to use client credentials (service acting as itself) and when not (acting for a user)
- Client authentication:
client_secret_basic, client_secret_post, private_key_jwt, mTLS
- Scopes and audience for service tokens, one client per service, least privilege
- Caching tokens until near expiry and handling a
401 by fetching a new one
- Rotating client secrets and keys without downtime
Free resources
Practice
In a local Keycloak (from the identity providers topic) create a confidential client with service accounts enabled, get a token with curl, and decode it. Then switch the client to signed-JWT authentication and get a token with a client_assertion instead of a secret.
Mutual TLS and certificate-bound tokens
In normal TLS only the server shows a certificate. In mutual TLS (mTLS) the client shows one too, and the server checks it against a CA it trusts, so both sides know who they are talking to before any HTTP is sent. It is common between internal services (service meshes such as Istio turn it on automatically), for B2B and banking APIs, and for IoT devices. The hard part is operations: issuing certificates, keeping lifetimes short and rotating them automatically.
RFC 8705 brings mTLS into OAuth in two ways. The client can authenticate to the authorization server with its certificate instead of a secret. And the server can issue certificate-bound access tokens: the token carries a cnf claim with the certificate's SHA-256 thumbprint (x5t#S256), and the API rejects the token unless it arrives over a TLS connection using that same certificate. A stolen token is then useless on its own; DPoP gives a similar guarantee at the application layer where mTLS is awkward, such as in browsers.
What to learn
- How the TLS handshake changes when the server requests a client certificate
- Running a private CA, issuing short-lived certificates and rotating them automatically
- mTLS terminated at a load balancer or gateway, and passing the verified identity on safely
- RFC 8705 client authentication and certificate-bound tokens with the
cnf / x5t#S256 claim
- Sender-constrained tokens: mTLS vs DPoP
Free resources
Practice
With openssl, create a small CA, a server certificate and a client certificate. Configure nginx (or any server) to require client certificates, then show that curl --cert client.crt --key client.key works and plain curl is rejected. Decode both certificates and compare their extended key usage.
Workload identity: no more long-lived keys
The most common way machine credentials leak is a long-lived key in a config file, a CI secret or a Git commit. Workload identity replaces stored keys with identity the platform already proves: the workload asks its environment for a short-lived, signed token and exchanges it for access. On AWS, an EC2 instance, Lambda function or ECS task assumes an IAM role and gets temporary credentials automatically. In Kubernetes, pods get short-lived, automatically rotated service account tokens (through the TokenRequest API since v1.22) that cloud providers can trust.
OIDC federation extends this to CI. A GitHub Actions job with permissions: id-token: write can request an OIDC token from https://token.actions.githubusercontent.com whose claims name the repository, branch and workflow; your cloud account trusts that issuer and only those claims, so deployments need no stored cloud keys. SPIFFE standardises the same idea across platforms: every workload gets a SPIFFE ID (spiffe://example.org/billing) and a short-lived identity document (an X.509 or JWT SVID), and SPIRE is its reference implementation.
What to learn
- Why long-lived keys leak, and what "short-lived, automatically rotated" credentials change
- Cloud roles for compute (for example AWS IAM roles) and the metadata endpoint that serves them
- Kubernetes service account tokens, projected volumes and audiences
- OIDC federation from CI: trusting an issuer and restricting the
sub, repository and branch claims
- SPIFFE IDs, SVIDs and SPIRE
Free resources
Practice
Replace a stored cloud access key in a GitHub Actions workflow with OIDC federation: create the identity provider and a role in your cloud account that trusts only your repository's main branch, add id-token: write to the workflow, delete the old secret, and check in the cloud audit log that the deployment used temporary credentials.
Service-to-service auth and identity propagation
When a user's request crosses several services (gateway → orders → payments), each hop needs to know both which service is calling and often which user it is acting for. Forwarding the user's original access token everywhere is simple but risky: every service can replay it to every other API in its audience. Token exchange (RFC 8693) is the cleaner pattern: a service swaps the incoming token at the authorization server for a new one with a narrower audience and scopes, optionally recording itself as the actor (act claim), so the payments API sees "orders, acting for user 42".
Other common pieces: an API gateway that validates external tokens at the edge (each service should still validate what it receives), short-lived internal JWTs minted by the gateway, and mTLS between services from a mesh for the service identity itself. Together these are the zero trust idea applied to service traffic: no request is trusted because it comes from "inside the network"; every call is authenticated and authorized.
1. Browser -> Gateway Authorization: Bearer <user token, aud=api>
2. Gateway validates the token, forwards it to the orders service
3. Orders -> Auth server token exchange: subject_token=<user token>
audience=payments, scope=payments.charge
4. Auth server -> Orders new token: sub=user42, aud=payments,
act={sub: orders-service}, expires in 5 min
5. Orders -> Payments (over mTLS) Authorization: Bearer <new token>
6. Payments checks aud, scope, act, and that user42 may pay this order
What to learn
- Service identity vs user identity, and why a service usually needs both
- Token forwarding vs token exchange (RFC 8693), audiences and the
act claim
- Validating tokens at the gateway and again in each service
- Internal tokens, service mesh mTLS, and network policies as defence in depth
- Zero trust for service traffic: authenticate and authorize every call
Free resources
Practice
Draw the token flow for a three-service checkout like the sketch above. Mark where each token is validated, what its audience and lifetime are, and what an attacker gets if they steal it at each hop. Then enable token exchange in a local Keycloak and perform step 3 with curl. See also microservices in System Design.
Am I ready? Stage 12 quiz
A nightly job calls your reporting API on its own behalf, with no user involved. Which OAuth grant fits?
- Authorization code with PKCE
- Client credentials
- Device authorization
- Implicit
Client credentials is for a client acting as itself. The other grants all involve a user signing in.
What does a certificate-bound access token (RFC 8705) protect against?
- Expired certificates on the API server
- Users choosing weak passwords
- A stolen token being used by someone without the client's private key
- The authorization server going offline
The token's cnf claim holds the client certificate's thumbprint, and the API only accepts it over a TLS connection made with that certificate.
How can a GitHub Actions workflow deploy to the cloud without a stored cloud access key?
- Request a short-lived OIDC token and exchange it for temporary credentials with a role that trusts that repository
- Put the access key in the workflow file but base64-encode it
- Use a personal access token from a developer's account
- Disable authentication on the deployment API
OIDC federation trusts the GitHub issuer and checks claims like the repository and branch, so no long-lived secret is stored anywhere.
The orders service needs to call the payments service for a user. Why use token exchange instead of forwarding the user's token?
- Forwarded tokens are always rejected by APIs
- Token exchange removes the need for HTTPS
- Token exchange makes tokens last longer
- It gives a new token with a narrow audience and scope that also records which service is acting
RFC 8693 lets each hop get just the access it needs, limiting what a leaked token can do, and the act claim keeps an audit trail of the caller.
Stage 13 · Advanced Enterprise identity management
In a company, identity is more than login: accounts live in a directory, get created and removed automatically as people join and leave, and access is reviewed and time-limited. This stage covers the systems that sit behind the IdP and the B2B features enterprise customers will ask your product for.
Directories: LDAP, Active Directory, Kerberos and Entra ID
A directory is the company's source of truth for people, groups and devices. LDAP is the protocol most on-premises directories speak: entries live in a tree and are named by a distinguished name such as uid=alice,ou=people,dc=example,dc=com, and applications bind (log in) and search with filters like (&(objectClass=person)(uid=alice)). Active Directory is Microsoft's directory: it speaks LDAP and uses Kerberos for single sign-on inside the Windows network, where a key distribution centre issues time-limited tickets so passwords never cross the wire.
In the cloud the directory is usually an identity provider such as Microsoft Entra ID (formerly Azure AD), often synchronised from on-premises AD, and apps talk to it with OIDC or SAML rather than LDAP. If your app does query LDAP directly, treat the filter like SQL: user input must be escaped, or *)(uid=* turns "find Alice" into "find everyone" (LDAP injection). Prefer binding as the user to check a password over comparing password attributes yourself, and always use LDAPS or StartTLS.
# Escape user input before putting it in an LDAP search filter (RFC 4515)
def escape_filter(value: str) -> str:
out = []
for ch in value:
if ch in '*()\\\0':
out.append('\\%02x' % ord(ch))
else:
out.append(ch)
return ''.join(out)
username = 'admin*)(uid=*' # attacker-controlled
print(f'(&(objectClass=person)(uid={escape_filter(username)}))')
# prints (&(objectClass=person)(uid=admin\2a\29\28uid=\2a))
print(escape_filter('alice'))
# prints alice
What to learn
- The LDAP data model: entries, attributes, object classes, DNs and the directory tree
- Bind and search operations, search filters and escaping user input (LDAP injection)
- Active Directory domains, groups and how Kerberos tickets give Windows single sign-on
- Cloud directories (Entra ID, Google Workspace) and syncing them from on-premises AD
- When an app should talk LDAP directly and when it should use OIDC or SAML via the IdP
Free resources
Practice
Run an OpenLDAP container locally, load three users and two groups from an LDIF file, then use ldapsearch to find a user and list a group's members. Connect Keycloak to it with "User federation" and log in to Keycloak's account console as one of the LDAP users.
SCIM provisioning and the joiner-mover-leaver lifecycle
SSO decides who can log in, but it doesn't create or delete accounts in your app. SCIM 2.0 (System for Cross-domain Identity Management, RFC 7643 for the schema and RFC 7644 for the protocol) is the standard REST API an IdP calls to provision users and groups: POST /Users when someone joins, PATCH when they change team, and active: false or DELETE when they leave.
The lifecycle is often called joiner-mover-leaver (JML). Leavers matter most: with SSO only, a fired employee can't log in again, but an existing session, API token or local password may keep working. A good SCIM endpoint deactivates the account, ends its sessions and revokes its tokens. Movers are the quiet risk: people collect access as they change roles unless group changes remove the old access too. Enterprise customers often require SCIM before they buy a SaaS product.
PATCH /scim/v2/Users/2819c223-7f76-453a-919d-413861904646 HTTP/1.1
Host: app.example.com
Authorization: Bearer <token the IdP was given>
Content-Type: application/scim+json
{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [
{ "op": "replace", "path": "active", "value": false }
]
}
What to learn
- Why SSO alone doesn't remove access, and what provisioning and deprovisioning add
- The SCIM User and Group resources,
externalId, and the core attributes
- SCIM operations: create, read, filter (
userName eq "alice"), PATCH and delete
- What deactivating a user must do in your app: end sessions, revoke tokens and API keys
- Joiner-mover-leaver processes and how group changes should remove old access
Free resources
Practice
Build a minimal SCIM endpoint for an app of yours with POST /Users, GET /Users?filter=userName eq "x" and PATCH /Users/{id}. Protect it with a bearer token, and make active: false delete the user's sessions. Test it with curl, then point a free Okta or Entra ID developer tenant at it.
Identity governance and privileged access (IGA and PAM)
Identity governance and administration (IGA) answers "who has access to what, and should they?". Its tools run access requests with approvals, periodic access reviews (managers re-certify their team's access, and anything not confirmed is removed), and separation of duties rules, for example that nobody can both create a supplier and approve its payments. Auditors for SOC 2, ISO 27001 and similar standards ask for this evidence.
Privileged access management (PAM) protects the accounts that can do the most damage: cloud admins, database owners, domain admins. The modern approach is no standing privilege: people hold normal access and request just-in-time elevation for a few hours, with a reason, approval, MFA and a recorded session. A small number of break-glass emergency accounts, with long random credentials kept offline and alerts on every use, keep you in if the IdP or MFA is down.
What to learn
- Access requests, approvals and periodic access reviews (re-certification)
- Separation of duties and toxic combinations of permissions
- Standing vs just-in-time privileged access, and time-limited role activation
- Break-glass accounts: how many, how they're stored, and alerting on every use
- Session recording, approvals and audit evidence for privileged actions
Free resources
Practice
Write a one-page access policy for a 30-person startup: which roles exist, who approves admin access, how long elevated access lasts, how often access is reviewed, and how the two break-glass accounts are stored and monitored. Then list which of these your current cloud provider can enforce for you.
Workforce vs customer identity, and B2B multi-tenancy
Workforce identity is for a company's own staff: one IdP, managed devices, strict policies. Customer identity (CIAM) is for the public: self sign-up, social login, passkeys, huge scale, low friction and privacy controls. A B2B SaaS product sits in between: each customer is an organisation (tenant) with its own members, roles, and often its own SSO connection and SCIM feed.
Design the tenant model early. A user may belong to several organisations, so roles belong to the membership, not the user. Let each organisation's admins invite users, manage roles and set policies (enforce SSO, require MFA) without your support team: this is delegated administration. When a company uses its own IdP you federate with it (see SSO for SaaS), and every query must be scoped to the current tenant (see enforcing authorization).
What to learn
- Workforce identity vs CIAM: different users, scale, UX and policies
- Organisations, memberships and per-organisation roles in a B2B data model
- Invitations, domain verification and delegated administration for customer admins
- Per-tenant policies: enforced SSO, MFA requirements and session lifetimes
- Guest and partner access (B2B collaboration) between two companies' directories
Free resources
Practice
Design the tables for a B2B app: users, organisations, memberships (with role), invitations and verified domains. Write the query that lists projects for the current user in the current organisation, then add a test proving a member of organisation A can't read organisation B's projects by changing an id in the URL.
Zero trust and continuous access evaluation
Zero trust drops the idea that anything inside the corporate network is safe. NIST SP 800-207 (2020) describes it: every request to a resource is authenticated and authorized on its own, using the identity of the user and the device, the request's context, and least privilege, and access is granted per session rather than per network. A VPN gives you network access; zero trust gives you access to one app, if your identity, device health and risk all pass.
Decisions also need to change while a session is open. If a user is disabled, a device is reported stolen or a password is reset, apps holding a one-hour token shouldn't wait an hour. The OpenID Foundation's Shared Signals Framework and its CAEP profile (Continuous Access Evaluation Profile, final since August 2025) let an IdP and apps send each other events such as "session revoked" or "credential changed" so access ends in seconds.
What to learn
- The zero trust principles in NIST SP 800-207 and why the network perimeter isn't trusted
- Policy decision and enforcement points, and inputs like device posture and risk
- Identity-aware proxies as a replacement for VPN access to internal apps
- Continuous access evaluation: why long-lived tokens are a problem when risk changes
- Shared Signals and CAEP events such as session revoked and credential change
Free resources
Practice
Take one internal tool (a dashboard, an admin panel) currently reachable over a VPN. Sketch how it would work behind an identity-aware proxy: which IdP, what device and MFA checks, what happens within a minute of the user being disabled, and what gets logged.
Am I ready? Stage 13 quiz
An app builds the LDAP filter (uid= + username + ) from a login form. What is the risk?
- Kerberos tickets expire too early
- The directory sends passwords in plain text
- LDAP injection: input like
*)(uid=* changes what the filter matches - SCIM provisioning stops working
Like SQL, an LDAP filter built from raw input can be rewritten by the attacker. Escape * ( ) \ and NUL, or use a library that builds filters safely.
A company uses SSO for your SaaS app. An employee leaves and is disabled in the IdP. What does SCIM add?
- Your app is told to deactivate the account, so sessions and API tokens can be revoked too
- It encrypts the employee's data so nobody can read it
- It replaces SAML or OIDC for logging in
- Nothing: disabling in the IdP already ends every session in every app
SSO stops new logins, but existing sessions and tokens live in your app. SCIM deprovisioning lets you clean them up immediately.
What does "just-in-time" privileged access mean?
- Admins get permanent access, but only during office hours
- Admin passwords are generated just before each audit
- Access reviews happen every day instead of every quarter
- People have no standing admin rights and request time-limited elevation when needed
No standing privilege means a stolen everyday account can't do admin damage; elevation needs a reason, approval and MFA, and expires on its own.
In a B2B SaaS app, a user belongs to two customer organisations. Where should their role be stored?
- On the user record, shared by both organisations
- On the membership that links the user to each organisation
- In the ID token only, never in your database
- In a cookie the browser keeps per organisation
The same person can be an admin in one tenant and a viewer in another, so the role belongs to the user-organisation membership.
Stage 14 · Advanced Authentication security
Attackers rarely break cryptography; they guess, reuse, phish and steal. This stage covers the attacks that actually take over accounts, how to detect them, and how to test your own login, recovery and session handling.
Brute force, credential stuffing and password spraying
Three password attacks need three different defences. Brute force tries many passwords against one account. Credential stuffing replays username and password pairs leaked from other sites, betting that people reuse them; each account sees only one attempt, but the attack comes from thousands of IP addresses. Password spraying tries one common password (Winter2026!) against many accounts, staying under per-account limits.
Layer the defences: throttle failed attempts per account and per IP or network, with growing delays rather than a hard lockout that lets anyone lock your users out (NIST SP 800-63B-4 caps consecutive failures per account at 100 before disabling that authenticator). Reject passwords found in breach corpora at sign-up and password change, check them on login too, give the same response for "no such user" and "wrong password", and push users to MFA or passkeys, which make stolen passwords useless on their own. Have I Been Pwned's range API checks a password without sending it:
# Have I Been Pwned "range" check: only the first 5 hex chars of the
# SHA-1 leave your server (k-anonymity), never the password.
import hashlib
def split_hash(password: str) -> tuple[str, str]:
digest = hashlib.sha1(password.encode()).hexdigest().upper()
return digest[:5], digest[5:]
prefix, suffix = split_hash('password')
print('GET https://api.pwnedpasswords.com/range/' + prefix)
# prints GET https://api.pwnedpasswords.com/range/5BAA6
# The API answers with SUFFIX:COUNT lines (sample, counts made up here)
sample = """003D68EB55068C33ACE09247EE4C639306B:3
1E4C9B93F3F0682250B6CF8331B7EE68FD8:52256179
1F2B668E8AABEF1C59E9EC6F82E3F3CD786:1"""
counts = dict(line.split(':') for line in sample.splitlines())
print('breached' if suffix in counts else 'not found', counts.get(suffix))
# prints breached 52256179
What to learn
- The difference between brute force, credential stuffing and password spraying, and how each looks in logs
- Throttling per account and per IP, increasing delays, and why hard lockouts can be abused
- Breached-password checks with k-anonymity (only a hash prefix leaves your server)
- Uniform error messages and timing so attackers can't enumerate valid usernames
- Why MFA, passkeys and bot defences change the economics of these attacks
Free resources
Practice
Add two limits to a login endpoint of yours: 5 failures per account per 15 minutes (with a growing delay) and 50 failures per IP per hour. Call the Pwned Passwords range API on registration. Then script 20 wrong logins with curl and check the responses and timing are identical for real and unknown usernames.
Phishing and adversary-in-the-middle attacks
Classic phishing copies a login page and collects passwords. Modern adversary-in-the-middle (AiTM) kits go further: the fake site is a reverse proxy in front of the real one, so the victim sees the real page, types their password and their OTP or approves the push, and the proxy keeps the session cookie the real site sets. The attacker then imports that cookie and is logged in, MFA and all.
Only phishing-resistant authenticators stop this: passkeys and other FIDO2/WebAuthn credentials are bound to the real origin, so the browser simply won't use them on examp1e-login.com, and smart-card or certificate-based login (PIV, mutual TLS) is similar. OTP codes, SMS and push approvals can all be relayed. Further layers: short session lifetimes for sensitive actions, re-authentication before changing email, password or MFA, alerts on new devices, and binding sessions to the device (see account takeover).
Victim Phishing proxy Real site
|-- password ----->|-- password ----------->|
|<-- OTP prompt ----|<-- OTP prompt ---------|
|-- 123456 ------->|-- 123456 ------------->|
| |<-- Set-Cookie: session-| attacker keeps it
|<-- "logged in" ---| |
Passkey: the browser checks the origin, sees the
proxy's domain, and never releases the credential.
What to learn
- How AiTM phishing kits relay passwords and one-time codes and steal the session cookie
- Which factors are phishing-resistant (passkeys, FIDO2 keys, PIV) and why origin binding matters
- Why OTP, SMS and push approvals can't stop a real-time relay
- Re-authentication before sensitive changes and alerts on new sign-ins
- Domain lookalikes, email authentication (SPF, DKIM, DMARC) and user reporting
Free resources
Practice
List every way to sign in and recover an account in an app you work on. Mark each as phishable or phishing-resistant, and write down what an AiTM attacker who relays the login would get (a session for how long? can they add their own MFA device?). Propose two changes that limit the damage.
Account takeover: recovery abuse and session theft
When login is strong, attackers go around it. Account recovery is the favourite: guessable security questions, reset links that don't expire, SMS reset codes after a SIM swap, or a help-desk agent talked into resetting MFA. Your recovery flow is only as strong as its weakest step, so give it the same care as login: single-use, short-lived reset tokens, notifications to the old email, a waiting period or extra checks before MFA can be removed, and strict identity checks for help-desk resets.
The other route is stealing what login produced. Info-stealer malware copies session cookies and refresh tokens straight out of the browser profile, skipping the password and MFA entirely. Limit the damage with shorter sessions for sensitive apps, refresh-token rotation with reuse detection, revoking sessions on password or MFA changes, and showing users their active sessions. Device Bound Session Credentials (DBSC), which Chrome made available on Windows in 2026, binds a session to a key kept in the device's TPM, so a copied cookie stops working elsewhere.
What to learn
- Secure password reset: random single-use tokens, short expiry, no user enumeration
- Changing email, phone or MFA safely: re-authentication, notifications and cooling-off periods
- Help-desk social engineering and how to verify a caller before resetting MFA
- Session and token theft by malware, and limits: rotation, revocation, short lifetimes
- Device-bound sessions (DBSC) and sender-constrained tokens (DPoP, mTLS)
Free resources
Practice
Attack your own password reset flow on localhost: does the token expire? Can it be used twice? Does an old token still work after a new one is issued? Does the response reveal whether the email exists? Is every session ended after the reset? Fix each problem you find and add a test for it.
Monitoring, risk-based authentication and bots
You can't stop what you can't see. Log every authentication event with a consistent vocabulary: login success and failure (with reason), MFA challenges, password and MFA changes, recovery, new devices, token refreshes, logouts and admin actions. Include the user id, IP, user agent, time and result, but never passwords, OTPs, tokens or full session ids. Alert a human on patterns: a spike in failures, many accounts from one IP, many IPs on one account, or a disabled break-glass account suddenly used.
Risk-based (adaptive) authentication uses those signals at login time: a known device in the usual city logs straight in; a new device, a TOR exit node or impossible travel triggers step-up MFA or a block. Bot defences (rate limits, proof-of-work, device signals, CAPTCHAs as a last resort since they hurt real users and accessibility) slow automated attacks.
# Flag a login that would need faster-than-airliner travel
from math import radians, sin, cos, asin, sqrt
from datetime import datetime
def km_between(a, b):
lat1, lon1, lat2, lon2 = map(radians, (*a, *b))
h = (sin((lat2 - lat1) / 2) ** 2
+ cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2)
return 2 * 6371 * asin(sqrt(h))
london, sydney = (51.5072, -0.1276), (-33.8688, 151.2093)
t1 = datetime.fromisoformat('2026-11-06T09:00')
t2 = datetime.fromisoformat('2026-11-06T11:30')
km = km_between(london, sydney)
speed = km / ((t2 - t1).total_seconds() / 3600)
print(f'{km:.0f} km in 2.5 h = {speed:.0f} km/h')
# prints 16994 km in 2.5 h = 6798 km/h
print('step-up or block' if speed > 1000 else 'ok')
# prints step-up or block
What to learn
- Which authentication events to log, and which secrets must never appear in logs
- Alerting rules for stuffing, spraying, unusual admin activity and break-glass use
- Risk signals: new device, location, impossible travel, IP reputation, time of day
- Adaptive responses: allow, step-up MFA, block, or notify the user
- Bot management and the cost of CAPTCHAs for real users and accessibility
Free resources
Practice
Emit structured JSON log lines for login success, login failure, MFA change and password reset in an app of yours. Write a query (or a small script over the log file) that flags any IP with failures on more than 10 different accounts in 10 minutes, then trigger it with a test script.
Testing authentication: ASVS and hands-on labs
The OWASP Application Security Verification Standard (ASVS) 5.0 is a checklist of security requirements you can test against, with three levels of rigour. Its chapters map almost one-to-one onto this roadmap: V6 Authentication, V7 Session Management, V8 Authorization, V9 Self-contained Tokens (JWTs) and V10 OAuth and OIDC. Pick a level, go through those chapters, and turn each requirement into a test or a review item.
Then attack your own app the way a tester would: enumerate usernames through messages and timing, bypass rate limits (other IPs, extra headers like X-Forwarded-For, changing the case of the username), skip the MFA step by going straight to the next URL, reuse reset tokens, tamper with JWTs and OAuth redirects. The PortSwigger Web Security Academy's free labs let you practise each one legally; the Web Security roadmap lists them.
What to learn
- ASVS 5.0 levels and the chapters V6 to V10 that cover authentication, sessions, authorization, tokens and OAuth
- Username enumeration through messages, status codes and response timing
- Rate-limit bypasses and MFA-step skipping, and how to test for them
- Turning requirements into automated tests that run in CI
- Writing a short, reproducible finding: steps, impact and fix
Free resources
Practice
Pick ASVS level 1 and go through chapters V6 and V7 for an app of yours. Mark each requirement pass, fail or not applicable, and turn three of the fails into automated tests. Then finish the PortSwigger Apprentice authentication labs.
Am I ready? Stage 14 quiz
Your logs show one failed login each on 8,000 different accounts, all with the password Summer2026!, from a few IPs. What attack is this?
- Credential stuffing
- Password spraying
- Brute force against one account
- Session fixation
Spraying tries one common password across many accounts to stay under per-account limits. Stuffing uses different leaked pairs per account.
An adversary-in-the-middle phishing kit is used against users with TOTP codes. What does the attacker end up with?
- Nothing, because TOTP codes expire after 30 seconds
- Only the password, since the code can't be relayed
- The TOTP seed, so they can make codes forever
- A valid session cookie for the real site
The proxy relays the password and code in real time and keeps the session cookie the real site sets. Only origin-bound credentials like passkeys stop this.
Why does the Pwned Passwords range API only receive the first 5 characters of the SHA-1 hash?
- So the service never learns which password you're checking (k-anonymity)
- Because SHA-1 hashes are only 5 characters long
- To make the request faster than sending a whole password
- So attackers can't use the API for brute force
Hundreds of breached hashes share each prefix; you compare the suffixes locally, so neither the password nor its full hash leaves your server.
Which item should never be written to your authentication logs?
- The user id and the result of the login
- The IP address and user agent
- The one-time code the user typed
- The time and the reason a login failed
Logs are read by many people and systems. Passwords, OTPs, tokens and session ids would turn the log into a way to log in.
Stage 15 · Advanced Spring Security implementations
Everything from the earlier stages, built for real with Spring Boot 4 and Spring Security 7: form login and sessions, a JWT-protected API, OIDC login, method-level authorization, your own authorization server, passkeys, one-time tokens and MFA, and tests for all of it. The examples form one small Maven project with one Spring profile per topic (--spring.profiles.active=api), and every file and test on this stage is compiled and run by our checker.
How Spring Security works: the filter chain
Spring Security is a chain of servlet filters that runs before your controllers. Spring Boot registers a DelegatingFilterProxy with the servlet container; it hands each request to Spring's FilterChainProxy, which picks the first SecurityFilterChain bean whose matcher fits the request and runs its filters in order: CSRF, logout, the login filters (form, OAuth2, bearer token, passkeys…), then AuthorizationFilter last. You configure a chain by declaring a SecurityFilterChain bean built from HttpSecurity; an app can have several, ordered with @Order and limited with securityMatcher.
A login filter turns credentials into an Authentication request and asks the AuthenticationManager, which tries its AuthenticationProviders (for example DaoAuthenticationProvider for passwords). The authenticated result, with the user's GrantedAuthority list (ROLE_ADMIN, SCOPE_messages.read, FACTOR_PASSWORD…), is stored in the SecurityContext, held per request by SecurityContextHolder and saved in the HTTP session between requests for browser logins. Add only spring-boot-starter-security and Boot locks every URL behind a generated login page and a random password printed at startup; your own SecurityFilterChain bean replaces that default. Spring Security 7 removed the old and() style and authorizeRequests: configure with lambdas and authorizeHttpRequests.
request
→ DelegatingFilterProxy (servlet container)
→ FilterChainProxy: first SecurityFilterChain whose matcher fits
CsrfFilter → LogoutFilter → UsernamePasswordAuthenticationFilter
→ BearerTokenAuthenticationFilter → … → ExceptionTranslationFilter
→ AuthorizationFilter (permit, deny, or 401/redirect to login)
→ DispatcherServlet → your @RestController
package com.example.auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
package com.example.auth.web;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String home() {
return "Hello! Try /me after you log in.";
}
// Spring MVC passes in the Authentication that the security
// filters stored in the SecurityContext for this request.
@GetMapping("/me")
public Map<String, Object> me(Authentication auth) {
List<String> authorities = auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.sorted()
.toList();
return Map.of("name", auth.getName(), "authorities", authorities);
}
@GetMapping("/admin")
public String admin() {
return "Admin area";
}
@GetMapping("/account/settings")
public String settings() {
return "Account settings";
}
}
# One app, one profile per example: --spring.profiles.active=api
spring:
profiles:
default: form
---
spring:
config:
activate:
on-profile: api
security:
oauth2:
resourceserver:
jwt:
# Spring reads <issuer>/.well-known/openid-configuration on
# first use, finds the JWKS URL and checks "iss" on every token.
issuer-uri: http://localhost:9000
audiences: messages-api
---
spring:
config:
activate:
on-profile: login
security:
oauth2:
client:
registration:
demo:
client-id: demo-web
client-secret: ${DEMO_CLIENT_SECRET}
scope: openid, profile, email
provider:
demo:
issuer-uri: http://localhost:9000
---
server:
port: 9000
spring:
config:
activate:
on-profile: authserver
security:
user:
name: ann
password: "{noop}change-me" # demo only
oauth2:
authorizationserver:
client:
demo-web:
registration:
client-id: demo-web
client-secret: "{noop}change-me-too"
client-authentication-methods: client_secret_basic
authorization-grant-types: authorization_code, refresh_token
redirect-uris: http://localhost:8080/login/oauth2/code/demo
post-logout-redirect-uris: http://localhost:8080/
scopes: openid, profile, email
require-proof-key: true # PKCE
reports-job: # machine-to-machine
registration:
client-id: reports-job
client-secret: "{noop}another-secret"
client-authentication-methods: client_secret_basic
authorization-grant-types: client_credentials
scopes: messages.read
What to learn
DelegatingFilterProxy, FilterChainProxy and how one of several SecurityFilterChain beans is chosen
- The main filters in order, and why
AuthorizationFilter runs last
Authentication, AuthenticationManager, AuthenticationProvider and GrantedAuthority
SecurityContextHolder and how the context is saved in the session between requests
- What Spring Boot configures when you add the starter, and what replaces it
- Reading the security log:
logging.level.org.springframework.security=TRACE
Free resources
Practice
Create the project on start.spring.io (Spring Web + Spring Security), add the controller above and start it. Open /me, log in with the generated password, and read the TRACE log for one request: write down every filter it passes through and where the SecurityContext came from on the second request.
Form login, passwords, sessions and CSRF
The classic server-rendered login from stage 2. formLogin() adds the login page and the POST /login handler; a UserDetailsService loads the user by name and a PasswordEncoder checks the password. Use PasswordEncoderFactories.createDelegatingPasswordEncoder(): it stores hashes as {bcrypt}$2a$10$…, so you can move to Argon2 later and upgrade old hashes as people log in. In production, implement UserDetailsService over your users table (or use JdbcUserDetailsManager) instead of the in-memory demo users.
Spring Security already does the session work from session lifecycle: it changes the session id at login (fixation protection), can limit concurrent sessions, and clears everything on logout. CSRF protection is on by default, so every form and every POST/PUT/DELETE from the browser must carry the token (Thymeleaf adds it to forms automatically; a single-page app can use csrf(c -> c.spa()), new in Spring Security 7). Remember-me adds a long-lived signed cookie: keep it optional, give it a strong key, and ask for the password again before sensitive actions.
package com.example.auth.form;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@Profile("form")
public class FormLoginConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/error").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults()) // GET+POST /login
.rememberMe(remember -> remember
.key("change-me-to-a-long-random-secret")
.tokenValiditySeconds(14 * 24 * 60 * 60))
.sessionManagement(session -> session
.sessionFixation(fix -> fix.changeSessionId())
.maximumSessions(3))
.logout(logout -> logout
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID"));
// CSRF protection is on by default: forms need the token.
return http.build();
}
// Stores "{bcrypt}$2a$10$..." so the algorithm can change later.
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
// Demo users in memory. A real app implements UserDetailsService
// over its users table (or uses JdbcUserDetailsManager).
@Bean
UserDetailsService users(PasswordEncoder encoder) {
var ann = User.withUsername("ann")
.password(encoder.encode("correct-horse-battery"))
.roles("USER")
.build();
var root = User.withUsername("root")
.password(encoder.encode("a-much-longer-admin-secret"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(ann, root);
}
}
What to learn
formLogin(), a custom login page, and the /login?error and logout flows
UserDetailsService, UserDetails and loading users from your database
DelegatingPasswordEncoder, the {id} prefix and upgrading hashes on login
- Session fixation protection, concurrent session limits and session timeouts
- CSRF tokens in forms and in single-page apps, and when disabling CSRF is safe
- Remember-me (hash-based vs persistent tokens) and its risks
Free resources
Practice
Run the form profile. Replace the in-memory users with a users table and your own UserDetailsService, store one user with a {bcrypt} hash, and check in DevTools that the JSESSIONID changes at login and that a POST without the CSRF token gets a 403.
Protecting an API with JWTs (resource server)
An API that accepts access tokens from an authorization server is an OAuth2 resource server. Add spring-boot-starter-security-oauth2-resource-server, set issuer-uri, and call oauth2ResourceServer(rs -> rs.jwt(…)). On the first request Spring fetches the issuer's discovery document, downloads the JWKS (and refreshes it when a new kid appears), then checks the signature, exp, nbf and iss of every token, plus aud when you set audiences. Exactly the checks from JWT validation, done for you.
By default each value in the scope claim becomes an authority named SCOPE_<value>, which you check with hasAuthority("SCOPE_messages.read"). If your IdP puts roles in a custom claim (Keycloak and Entra ID both do), map them with your own converter as below. Make the API stateless: no session, no cookies, and so no CSRF token needed. A missing or bad token gets a 401 with a WWW-Authenticate: Bearer header; a valid token without the right scope gets a 403. Spring Security can also accept opaque tokens through introspection and DPoP-bound tokens.
package com.example.auth.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@Profile("api")
public class ResourceServerConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/messages/**")
.hasAuthority("SCOPE_messages.read")
.requestMatchers(HttpMethod.POST, "/api/messages/**")
.hasAuthority("SCOPE_messages.write")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer(rs -> rs.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtConverter())))
// No session and no cookies: every request carries a token,
// so CSRF protection isn't needed for this API.
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable());
return http.build();
}
// "scope": "messages.read" becomes SCOPE_messages.read (the default)
// and a custom "roles": ["admin"] claim becomes ROLE_ADMIN.
static Converter<Jwt, Collection<GrantedAuthority>> authorities() {
var scopes = new JwtGrantedAuthoritiesConverter();
return jwt -> {
Collection<GrantedAuthority> all =
new ArrayList<>(scopes.convert(jwt));
List<String> roles = jwt.getClaimAsStringList("roles");
if (roles != null) {
roles.forEach(r -> all.add(
new SimpleGrantedAuthority("ROLE_" + r.toUpperCase())));
}
return all;
};
}
static JwtAuthenticationConverter jwtConverter() {
var converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities());
return converter;
}
}
package com.example.auth.api;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MessageController {
@GetMapping("/api/messages")
public List<String> list() {
return List.of("hello", "world");
}
// The validated token is available as a Jwt: "sub" identifies
// the user, never a user id sent in the request body.
@PostMapping("/api/messages")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, String> create(@AuthenticationPrincipal Jwt jwt,
@RequestBody String text) {
return Map.of("author", jwt.getSubject(), "text", text);
}
}
What to learn
issuer-uri vs jwk-set-uri, and what Spring checks in every token
- Checking the audience so tokens meant for another API are refused
- Scopes as
SCOPE_ authorities and mapping custom role claims with a converter
- Stateless session policy, and why a token-only API doesn't need CSRF protection
- Reading the token in a controller with
@AuthenticationPrincipal Jwt
- When to use opaque tokens and introspection instead of JWTs
Free resources
Practice
Run the authserver profile on port 9000 and the api profile on 8080. Get a token for reports-job with curl -u reports-job:another-secret -d grant_type=client_credentials -d scope=messages.read http://localhost:9000/oauth2/token, decode it, then call GET /api/messages with it. Try a POST with the same token and explain the 403. (To pass the audience check, have the authorization server add messages-api to aud with an OAuth2TokenCustomizer, or remove audiences while you experiment.)
Log in with OpenID Connect (OAuth2 client)
To let users sign in with Keycloak, Okta, Entra ID, Google or your own authorization server, add spring-boot-starter-security-oauth2-client, register the client in application.yml (the login profile above) and call oauth2Login(). Spring runs the authorization code flow with PKCE, state and nonce, validates the ID token, and creates a normal server session for the user. The access and refresh tokens stay on the server in the OAuth2AuthorizedClientService; the browser only ever gets the session cookie. That is the backend-for-frontend pattern, the safest way to log in a browser app.
The user's id is the sub claim from that issuer, never the email. For logout, also end the session at the IdP with OidcClientInitiatedLogoutSuccessHandler (OIDC RP-initiated logout); Spring Security also supports OIDC back-channel logout. To call other APIs on the user's behalf, inject an OAuth2AuthorizedClientManager or use the @ClientRegistrationId support for HTTP service clients and Spring refreshes tokens for you.
package com.example.auth.login;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@Profile("login")
public class OAuth2LoginConfig {
@Bean
SecurityFilterChain web(HttpSecurity http,
ClientRegistrationRepository clients) {
// After local logout, also end the session at the IdP
// (OIDC RP-initiated logout), then come back to "/".
var oidcLogout = new OidcClientInitiatedLogoutSuccessHandler(clients);
oidcLogout.setPostLogoutRedirectUri("{baseUrl}/");
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/error").permitAll()
.anyRequest().authenticated())
// Authorization code + PKCE with the IdP; the tokens stay
// on the server and the browser only gets a session cookie.
.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout.logoutSuccessHandler(oidcLogout));
return http.build();
}
}
What to learn
- Client registrations and providers in
application.yml, with the secret from the environment
- The redirect URI pattern
/login/oauth2/code/{registrationId}
- What
oauth2Login() checks: state, PKCE, nonce and the ID token
OidcUser, claims, and mapping IdP groups to your own authorities
- RP-initiated and back-channel logout
- Calling downstream APIs with the user's access token and automatic refresh
Free resources
Practice
Start Keycloak in Docker, create a realm, a user and a confidential client with redirect URI http://localhost:8080/login/oauth2/code/demo. Point the login profile at it (issuer-uri = the realm URL), log in, open /me and find the code_challenge and state parameters in the Network tab. Then log out and check that the Keycloak session ended too.
Method security and custom authorization rules
URL rules in the filter chain are coarse: "only admins under /admin". Most real rules are about data: "only the owner may read this document". @EnableMethodSecurity turns on @PreAuthorize (checked before the method runs, can use its parameters as #id) and @PostAuthorize (checked on the returnObject), written in SpEL. A denied call throws AuthorizationDeniedException, which becomes a 403.
Keep expressions short and move real logic into a bean you can unit test, called as @access.canDelete(#id, authentication). This is how you fix the IDOR bugs from authorization enforcement: the id in the URL is never enough on its own. For rules the annotations can't express, implement an AuthorizationManager, and for whole-app policies consider an external engine (ABAC, ReBAC).
package com.example.auth.docs;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
// Turns on @PreAuthorize, @PostAuthorize and friends for all beans.
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}
package com.example.auth.docs;
public record Document(long id, String owner, String title) {
}
package com.example.auth.docs;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class DocumentService {
private final Map<Long, Document> docs = new ConcurrentHashMap<>(Map.of(
1L, new Document(1, "ann", "Ann's notes"),
2L, new Document(2, "bob", "Bob's plan")));
// Checked after loading: only the owner (or an admin) gets it back.
// This is the fix for IDOR: the id alone is never enough.
@PostAuthorize("returnObject.owner == authentication.name"
+ " or hasRole('ADMIN')")
public Document get(long id) {
return docs.get(id);
}
// Checked before the method runs, using a method parameter
// and a bean: @access.canDelete(...) below.
@PreAuthorize("@access.canDelete(#id, authentication)")
public void delete(long id) {
docs.remove(id);
}
@PreAuthorize("hasRole('ADMIN')")
public int count() {
return docs.size();
}
}
package com.example.auth.docs;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
// Authorization rules in plain Java, easy to unit test.
@Component("access")
public class DocumentAccess {
public boolean canDelete(long id, Authentication auth) {
boolean admin = auth.getAuthorities().stream()
.anyMatch(a -> "ROLE_ADMIN".equals(a.getAuthority()));
// Real code would look up the owner in the database.
boolean owner = id == 1 && "ann".equals(auth.getName());
return admin || owner;
}
}
What to learn
authorizeHttpRequests rules: order, requestMatchers, deny by default
@EnableMethodSecurity, @PreAuthorize, @PostAuthorize and SpEL with parameters
hasRole vs hasAuthority and the ROLE_ prefix
- Delegating checks to a bean and unit testing that bean
- Custom
AuthorizationManager implementations and role hierarchies
- Why method security only works on calls through the Spring proxy (not
this.method())
Free resources
Practice
Add a PUT /documents/{id} endpoint backed by DocumentService. Write one test proving Ann can edit her document and one proving Bob gets a 403 for it, then move the owner check into a real database query and keep both tests green.
Running your own authorization server
Spring Authorization Server lets you build your own OAuth 2.1 / OpenID Connect provider in Spring Boot: authorization code with PKCE, client credentials, refresh tokens, device authorization, token exchange, introspection, revocation, discovery and JWKS endpoints, consent pages and client registration. It started as a separate project; since Spring Security 7.0 it is part of Spring Security (artifact spring-security-oauth2-authorization-server, Boot starter spring-boot-starter-security-oauth2-authorization-server), and its 1.5.x line was the last stand-alone release.
Before you build one, re-read build vs buy: Keycloak or a hosted IdP gives you admin screens, MFA, federation and user management for free. Building your own makes sense when identity is core to your product or you need deep customisation. The minimal setup is clients in application.yml (the authserver profile above) plus two filter chains: one for the protocol endpoints and one for the login form. For production, replace the in-memory parts: store clients, authorizations and consents in the database (JDBC implementations are included), keep signing keys in a key store with rotation (key management), and put real user login with MFA in front.
package com.example.auth.authserver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
@Configuration
@Profile("authserver")
public class AuthorizationServerConfig {
// Chain 1: only the OAuth2/OIDC endpoints (/oauth2/authorize,
// /oauth2/token, /oauth2/jwks, /.well-known/openid-configuration...)
@Bean
@Order(1)
SecurityFilterChain authServer(HttpSecurity http) {
http
.oauth2AuthorizationServer(as -> {
http.securityMatcher(as.getEndpointsMatcher());
as.oidc(Customizer.withDefaults()); // OpenID Connect
})
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
// Browsers that aren't logged in go to the login page.
.exceptionHandling(ex -> ex.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)));
return http.build();
}
// Chain 2: everything else, including the login form users see.
@Bean
@Order(2)
SecurityFilterChain web(HttpSecurity http) {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}
What to learn
- The protocol endpoints it adds and the two-chain setup
RegisteredClient: grant types, redirect URIs, PKCE, scopes, consent and token settings
- Signing keys: the
JWKSource bean and rotating keys without breaking clients
- Customising tokens with
OAuth2TokenCustomizer (audience, roles, tenant)
- JDBC-backed clients, authorizations and consents for production
- When building your own IdP is a bad idea
Free resources
Practice
Run the authserver profile and open http://localhost:9000/.well-known/openid-configuration. Get a client credentials token with curl, then run the login profile against it and sign in as ann. Finally add an OAuth2TokenCustomizer that puts messages-api in aud, so the api profile accepts its tokens.
Passkeys, one-time tokens and MFA
Spring Security has three building blocks for stronger login. Passkeys: add spring-security-webauthn and webAuthn(), and users register a passkey at /webauthn/register and can then sign in with it from the login page (rpId and allowedOrigins must match your real domain; store credentials with the JDBC repositories in production). One-time token login: oneTimeTokenLogin() creates a single-use token for a username; you deliver it, usually as a magic link by email, by writing a OneTimeTokenGenerationSuccessHandler. It is not TOTP: for authenticator-app codes you still need a library and your own enrolment screens.
MFA arrived in Spring Security 7.0. Every login method adds a factor authority (FACTOR_PASSWORD, FACTOR_OTT, FACTOR_WEBAUTHN…), and an AuthorizationManagerFactory from AuthorizationManagerFactories.multiFactor() can require several of them, for every URL or only where you choose. If a factor is missing, Spring sends the user to the login page for that factor. You can also require a factor proved recently (validDuration), which gives you step-up authentication for sensitive pages.
package com.example.auth.mfa;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authorization.AuthorizationManagerFactories;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authorization.EnableMultiFactorAuthentication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@Profile("mfa")
// Turns MFA support on without forcing it on every URL.
@EnableMultiFactorAuthentication(authorities = {})
public class MfaConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) {
// A password AND a second factor: a one-time token (magic link)
// or a passkey. Each login method adds a FACTOR_* authority.
var mfa = AuthorizationManagerFactories.multiFactor()
.requireFactors(FactorGrantedAuthority.PASSWORD_AUTHORITY,
FactorGrantedAuthority.OTT_AUTHORITY)
.build();
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/error").permitAll()
.requestMatchers("/admin/**").access(mfa.hasRole("ADMIN"))
.requestMatchers("/account/**").access(mfa.authenticated())
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.oneTimeTokenLogin(Customizer.withDefaults())
// Passkeys: register at /webauthn/register, sign in from
// the default login page. rpId must be your real domain.
.webAuthn(passkeys -> passkeys
.rpName("Example App")
.rpId("localhost")
.allowedOrigins("http://localhost:8080"));
return http.build();
}
@Bean
UserDetailsService users() {
var encoder =
PasswordEncoderFactories.createDelegatingPasswordEncoder();
return new InMemoryUserDetailsManager(User.withUsername("ann")
.password(encoder.encode("correct-horse-battery"))
.roles("USER", "ADMIN")
.build());
}
}
package com.example.auth.mfa;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.ott.OneTimeToken;
import org.springframework.security.web.authentication.ott.OneTimeTokenGenerationSuccessHandler;
import org.springframework.security.web.authentication.ott.RedirectOneTimeTokenGenerationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
// Spring Security creates the one-time token; you deliver it.
// DEMO ONLY: this logs the link. A real app e-mails it to the user
// and never writes tokens to logs.
@Component
@Profile("mfa")
public class MagicLinkSender implements OneTimeTokenGenerationSuccessHandler {
private static final Logger log =
LoggerFactory.getLogger(MagicLinkSender.class);
private final OneTimeTokenGenerationSuccessHandler next =
new RedirectOneTimeTokenGenerationSuccessHandler("/login/ott");
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
OneTimeToken token)
throws IOException, ServletException {
String link = UriComponentsBuilder
.fromUriString("http://localhost:8080/login/ott")
.queryParam("token", token.getTokenValue())
.toUriString();
log.info("Magic link for {}: {}", token.getUsername(), link);
next.handle(request, response, token);
}
}
What to learn
webAuthn(): rpId, allowed origins, registration and credential storage
oneTimeTokenLogin(), delivering magic links safely and token expiry
- One-time tokens vs TOTP codes, and what Spring does and doesn't provide
- Factor authorities and
@EnableMultiFactorAuthentication
- Requiring MFA only on some URLs, and recent-authentication rules with
validDuration
Free resources
Practice
Run the mfa profile on http://localhost:8080. Log in with the password, open /account/settings and follow the magic link from the log to finish the second factor. Then register a passkey at /webauthn/register, change the rule to accept a password plus a passkey, and require the password again within 15 minutes for /admin.
Testing your security configuration
Security rules are code, and a missing rule is a silent data leak, so test them like code. spring-security-test (pulled in by the Boot -test starters) gives you @WithMockUser for method tests and MockMvc request post-processors: user(), csrf(), httpBasic(), formLogin(), jwt() and oidcLogin(). They put an authenticated user in the request without a real IdP, so the tests run in milliseconds. jwt() skips the signature check but still goes through your authorization rules.
Test the negative cases first: no login (401 or a redirect to login), the wrong role or scope (403), a missing CSRF token (403), another user's data (denied). With Spring Boot 4, @AutoConfigureMockMvc comes from the spring-boot-starter-webmvc-test module, and MockMvcTester gives AssertJ-style assertions. The six test classes below (23 tests) cover every profile on this stage and are run by our checker.
package com.example.auth.form;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.HttpStatus;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("form")
class FormLoginTest {
@Autowired
MockMvcTester mvc;
@Test
void anonymousUsersAreSentToTheLoginPage() {
assertThat(mvc.get().uri("/me"))
.hasStatus3xxRedirection()
.hasRedirectedUrl("/login");
}
@Test
void rightPasswordLogsIn() {
assertThat(mvc.perform(formLogin()
.user("ann").password("correct-horse-battery")))
.hasRedirectedUrl("/");
}
@Test
void wrongPasswordFails() {
assertThat(mvc.perform(formLogin()
.user("ann").password("guess")))
.hasRedirectedUrl("/login?error");
}
@Test
@WithMockUser(username = "ann", roles = "USER")
void usersCannotOpenTheAdminPage() {
assertThat(mvc.get().uri("/admin")).hasStatus(HttpStatus.FORBIDDEN);
}
@Test
@WithMockUser(username = "ann")
void postWithoutCsrfTokenIsRejected() {
assertThat(mvc.post().uri("/logout"))
.hasStatus(HttpStatus.FORBIDDEN);
assertThat(mvc.post().uri("/logout").with(csrf()))
.hasRedirectedUrl("/");
}
}
package com.example.auth.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("api")
class ResourceServerTest {
@Autowired
MockMvcTester mvc;
@Test
void noTokenMeans401() {
assertThat(mvc.get().uri("/api/messages"))
.hasStatus(HttpStatus.UNAUTHORIZED)
.headers().containsHeader("WWW-Authenticate");
}
// jwt() skips signature checks and builds the Authentication
// with our converter, so the scope mapping is tested for real.
@Test
void readScopeCanRead() {
assertThat(mvc.get().uri("/api/messages")
.with(jwt().jwt(t -> t.claim("scope", "messages.read"))))
.hasStatusOk();
}
@Test
void readScopeCannotWrite() {
assertThat(mvc.post().uri("/api/messages")
.contentType(MediaType.TEXT_PLAIN).content("hi")
.with(jwt().jwt(t -> t.claim("scope", "messages.read"))))
.hasStatus(HttpStatus.FORBIDDEN);
}
@Test
void writeScopeCreatesAMessageAsTheTokenSubject() {
assertThat(mvc.post().uri("/api/messages")
.contentType(MediaType.TEXT_PLAIN).content("hi")
.with(jwt().jwt(t -> t.subject("ann")
.claim("scope", "messages.write"))))
.hasStatus(HttpStatus.CREATED)
.bodyJson().extractingPath("$.author").isEqualTo("ann");
}
@Test
void rolesClaimBecomesRoleAuthority() {
assertThat(mvc.get().uri("/admin")
.with(jwt().jwt(t -> t.claim("roles", List.of("admin")))
.authorities(ResourceServerConfig.authorities())))
.hasStatusOk();
}
}
package com.example.auth.docs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
@SpringBootTest
class DocumentServiceTest {
@Autowired
DocumentService documents;
@Test
@WithMockUser(username = "ann")
void ownersCanReadTheirDocument() {
assertThat(documents.get(1).title()).isEqualTo("Ann's notes");
}
@Test
@WithMockUser(username = "ann")
void otherPeoplesDocumentsAreDenied() {
assertThatThrownBy(() -> documents.get(2))
.isInstanceOf(AuthorizationDeniedException.class);
}
@Test
@WithMockUser(username = "boss", roles = "ADMIN")
void adminsCanReadAnyDocument() {
assertThat(documents.get(2).owner()).isEqualTo("bob");
assertThat(documents.count()).isEqualTo(2);
}
@Test
@WithMockUser(username = "bob")
void onlyTheOwnerOrAnAdminCanDelete() {
assertThatThrownBy(() -> documents.delete(1))
.isInstanceOf(AuthorizationDeniedException.class);
}
}
package com.example.auth.login;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest(properties = "DEMO_CLIENT_SECRET=test-secret")
@AutoConfigureMockMvc
@ActiveProfiles("login")
class OAuth2LoginTest {
// Replaces the issuer-uri registration so the test needs no IdP.
@TestConfiguration
static class FakeIdp {
@Bean
ClientRegistrationRepository clients() {
return new InMemoryClientRegistrationRepository(
ClientRegistration.withRegistrationId("demo")
.clientId("demo-web").clientSecret("test-secret")
.authorizationGrantType(
AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile")
.authorizationUri("https://idp.test/authorize")
.tokenUri("https://idp.test/token")
.jwkSetUri("https://idp.test/jwks")
.userNameAttributeName("sub")
.build());
}
}
@Autowired
MockMvcTester mvc;
@Test
void anonymousUsersStartTheLoginAtTheIdp() {
assertThat(mvc.get().uri("/me"))
.hasStatus3xxRedirection()
.hasRedirectedUrl("/oauth2/authorization/demo");
}
@Test
void theAuthorizationRequestUsesPkce() {
assertThat(mvc.get().uri("/oauth2/authorization/demo"))
.hasStatus3xxRedirection()
.redirectedUrl()
.startsWith("https://idp.test/authorize?")
.contains("code_challenge_method=S256", "state=", "nonce=");
}
@Test
void loggedInUsersSeeTheirClaims() {
assertThat(mvc.get().uri("/me")
.with(oidcLogin().idToken(t -> t.subject("user-42"))))
.hasStatusOk()
.bodyJson().extractingPath("$.name").isEqualTo("user-42");
}
}
package com.example.auth.authserver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("authserver")
class AuthorizationServerTest {
@Autowired
MockMvcTester mvc;
@Test
void publishesOpenIdDiscovery() {
assertThat(mvc.get().uri("/.well-known/openid-configuration"))
.hasStatusOk()
.bodyJson().extractingPath("$.token_endpoint")
.isEqualTo("http://localhost/oauth2/token");
}
@Test
void machineClientGetsAnAccessToken() {
assertThat(mvc.post().uri("/oauth2/token")
.param("grant_type", "client_credentials")
.param("scope", "messages.read")
.with(httpBasic("reports-job", "another-secret")))
.hasStatusOk()
.bodyJson().extractingPath("$.token_type")
.isEqualTo("Bearer");
}
@Test
void wrongClientSecretIsRejected() {
assertThat(mvc.post().uri("/oauth2/token")
.param("grant_type", "client_credentials")
.with(httpBasic("reports-job", "wrong")))
.hasStatus(HttpStatus.UNAUTHORIZED);
}
}
package com.example.auth.mfa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.core.authority.FactorGrantedAuthority.OTT_AUTHORITY;
import static org.springframework.security.core.authority.FactorGrantedAuthority.PASSWORD_AUTHORITY;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("mfa")
class MfaTest {
@Autowired
MockMvcTester mvc;
// A logged-in "ann" who proved the given factors.
static RequestPostProcessor annWith(String... factors) {
var authorities = java.util.Arrays.stream(factors)
.map(FactorGrantedAuthority::fromAuthority)
.toList();
return user("ann").authorities(authorities);
}
@Test
void passwordAloneIsEnoughForNormalPages() {
assertThat(mvc.get().uri("/me").with(annWith(PASSWORD_AUTHORITY)))
.hasStatusOk();
}
@Test
void settingsAskForTheSecondFactor() {
assertThat(mvc.get().uri("/account/settings")
.with(annWith(PASSWORD_AUTHORITY)))
.hasStatus3xxRedirection();
}
@Test
void passwordPlusOneTimeTokenOpensSettings() {
assertThat(mvc.get().uri("/account/settings")
.with(annWith(PASSWORD_AUTHORITY, OTT_AUTHORITY)))
.hasStatusOk();
}
}
What to learn
@WithMockUser and testing method security without HTTP
- MockMvc post-processors:
user(), csrf(), jwt(), oidcLogin(), httpBasic()
MockMvcTester assertions on status, redirects, headers and JSON
- Replacing the IdP in tests with a test
ClientRegistrationRepository
- A negative test for every rule: unauthenticated, wrong role or scope, missing CSRF, someone else's data
Free resources
Practice
Delete one rule from ResourceServerConfig (for example the POST scope check) and confirm a test fails. Then write a test that loops over every endpoint in your app and asserts that an anonymous request never gets a 200, except the ones you list as public.
Am I ready? Stage 15 quiz
Your app has two SecurityFilterChain beans. Which one handles a request?
- Both, one after the other
- The one declared last in the source file
- The first one, by
@Order, whose security matcher fits the request - The one with the most rules
FilterChainProxy runs exactly one chain per request: the first match. That's why the authorization server chain uses securityMatcher and @Order(1).
A JWT resource server gets a valid token whose scope claim is messages.read. Which authority does Spring give it by default?
SCOPE_messages.readROLE_messages.readmessages.read- None until you write a converter
The default JwtGrantedAuthoritiesConverter adds the SCOPE_ prefix. You need your own converter only for custom claims such as roles.
Where are the user's access and refresh tokens kept with oauth2Login()?
- In
localStorage, so the SPA can read them - In a JavaScript-readable cookie
- In the URL fragment after login
- On the server, linked to the user's session
The browser only gets an HttpOnly session cookie, so an XSS bug can't steal the tokens. This is the backend-for-frontend pattern.
With Spring Security 7 MFA, how does Spring know a user proved a second factor?
- It reads an
mfa=true request parameter - Each login method adds a factor authority such as
FACTOR_OTT - It asks the IdP on every request
- The session id changes length
Factor authorities (FACTOR_PASSWORD, FACTOR_OTT, FACTOR_WEBAUTHN…) are added as each factor succeeds, and MFA rules simply require several of them.
Stage 16 · Professional Production architecture
Put it all together for a real system: where identity lives, how browsers, APIs and services get their tokens, how keys rotate without downtime, and what happens when the identity provider is slow or down. The stage ends with a capstone that uses most of the roadmap.
Reference architecture and build vs buy
Most production systems converge on the same shape: one central identity provider (IdP) handles login, MFA, passkeys, federation and token issuing; browser apps talk to a backend for frontend that keeps tokens server-side; APIs are OAuth resource servers that validate access tokens and make their own authorization decisions; services call each other with their own workload identity. Apps never see passwords, and every component validates what it receives.
Build vs buy: writing your own login is easy; writing secure recovery, MFA, passkeys, SSO for every customer's IdP, SCIM, breached-password checks, audit logs and compliance evidence is years of work. Most teams use a hosted IdP (Auth0, Okta, Microsoft Entra, Amazon Cognito and others) or run an open-source one (Keycloak, Zitadel, Authentik and others). Choose by: protocols supported, B2B features, pricing at your user count, data residency, export of users (including password hashes) if you leave, and who is on call when it breaks.
Browser ──cookie──> BFF ──access token──> API gateway ──> Orders API
│ │ │
└──login──> IdP <─┘ (code + PKCE, refresh) │ client
(MFA, passkeys, SSO, SCIM) <── credentials ┘ token for
Billing API
What to learn
- The roles in a reference architecture: IdP, BFF, gateway, resource servers, workloads
- Where tokens are issued, where they are validated, and where authorization decisions live
- Build vs buy: the hidden work behind recovery, MFA, SSO, SCIM and audits
- Choosing an IdP: protocols, B2B features, pricing, data residency and lock-in
- Migrating users between IdPs, including password hashes and lazy migration on login
Free resources
Practice
Draw the auth architecture of a system you know (or a made-up shop with a web app, a mobile app, three APIs and a nightly job). Mark every token: who issues it, its audience, lifetime, where it's stored and who validates it. Then write a one-page build vs buy comparison of two IdPs for it.
Backend for frontend, token handlers and API gateways
A single-page app that holds access and refresh tokens in JavaScript loses them to any XSS bug. The backend for frontend (BFF) pattern fixes that: a small server on the app's own domain runs the OAuth code flow as a confidential client, keeps the tokens server-side, and gives the browser only an HttpOnly, Secure, SameSite session cookie. API calls go through the BFF, which attaches the access token. RFC 10017, "OAuth 2.0 for Browser-Based Applications" (Best Current Practice, August 2026), describes three architectures: BFF (strongest), token-mediating backend, and a pure browser client (only with extra care).
An API gateway in front of your services can do coarse checks at the edge: validate the token's signature, issuer, audience and expiry, enforce rate limits, and reject anonymous traffic early. Services must still check fine-grained permissions themselves (does this user own this order?), and should still validate the token if anything can reach them without going through the gateway.
What to learn
- Why tokens in browser JavaScript are risky, and what a BFF keeps on the server
- The three architectures in RFC 10017 and their trade-offs
- BFF details: session cookie flags, CSRF protection, token refresh and logout
- What an API gateway should check at the edge and what must stay in each service
- Token translation at the edge: turning an external token into an internal one
Free resources
Practice
Convert a SPA that stores tokens in localStorage into a BFF setup: the BFF runs the code flow with PKCE against a local Keycloak, stores tokens in its server session, and proxies /api/* with the access token. Confirm in DevTools that no token is visible to JavaScript and that logout ends both the BFF and IdP sessions. (Spring users: see OAuth 2.0 login with Spring.)
Signing keys, JWKS rotation and secrets
Every token you trust is only as safe as the key that signed it. Keep private signing keys in a KMS or HSM where possible, so the key can sign but never be exported; otherwise in a secrets manager, never in code, images or environment files committed to Git. Publish only public keys, in a JWKS document, each with a kid.
Rotate on a schedule and be ready to rotate in an emergency. Rotation without downtime needs overlap: publish the new public key first, wait until every client's JWKS cache has picked it up, start signing with it, and remove the old key only after the last token signed with it has expired. In an emergency (a leaked key) you remove the old key at once and accept that its tokens fail. The same overlap idea applies to client secrets, API keys and TLS certificates.
# Plan a signing-key rotation with overlap (all times UTC)
from datetime import datetime, timedelta
token_ttl = timedelta(hours=1) # longest access token lifetime
jwks_cache = timedelta(hours=24) # how long clients cache the JWKS
new_key_published = datetime(2026, 12, 1, 9, 0)
# 1. Publish the new public key in the JWKS, keep signing with the old one
# 2. Start signing with the new key once every cache has seen it
start_signing = new_key_published + jwks_cache
# 3. Remove the old key once no unexpired token can still use it
remove_old = start_signing + token_ttl
for step, when in [('publish new key', new_key_published),
('sign with new key', start_signing),
('remove old key', remove_old)]:
print(f'{when:%Y-%m-%d %H:%M} {step}')
# prints 2026-12-01 09:00 publish new key
# prints 2026-12-02 09:00 sign with new key
# prints 2026-12-02 10:00 remove old key
What to learn
- KMS, HSM and secrets managers: what each protects and when to use which
- JWKS documents,
kid selection, and caching rules on the client side
- Planned rotation with overlapping keys, and emergency rotation after a leak
- Rotating client secrets, API keys and certificates without downtime
- Detecting leaked secrets: secret scanning in Git and CI, and alerting on use
Free resources
Practice
Rotate the realm signing key in a local Keycloak while an API keeps validating tokens: add a new key with a higher priority, watch the JWKS endpoint list both keys, confirm old tokens still validate, then disable and delete the old key. Write the runbook for doing it in production, including the emergency version.
Reliability, scaling and IdP outages
When the IdP is down, nobody can log in, so plan for it. Design so that already-logged-in users keep working: APIs validate JWTs locally with cached public keys instead of calling the IdP on every request, and BFF sessions outlive a short IdP outage. Cache the JWKS, refresh it in the background, refetch on an unknown kid but only so often, so tokens with made-up kids can't flood the IdP. Use opaque tokens and introspection only where instant revocation is worth the extra calls, and cache the result briefly.
Treat the IdP and the session store as tier-0 dependencies: run them highly available (several nodes, a replicated database, multiple zones or regions), load-test login separately because password hashing is deliberately expensive, rate-limit login and token endpoints, and set timeouts and circuit breakers on every call to them. Know your graceful-degradation choices in advance, for example letting existing sessions continue but pausing new sign-ups.
# A JWKS cache: refresh on an unknown kid, but at most once a minute,
# so forged tokens with random kids can't hammer the identity provider
import time
class JwksCache:
def __init__(self, fetch, min_refresh=60, clock=time.monotonic):
self.fetch, self.min_refresh, self.clock = fetch, min_refresh, clock
self.keys, self.last = fetch(), clock()
def key_for(self, kid):
stale = self.clock() - self.last >= self.min_refresh
if kid not in self.keys and stale:
self.keys, self.last = self.fetch(), self.clock()
return self.keys.get(kid) # None means reject the token
fetches = []
published = {'k1': 'public-key-1'}
def fetch():
fetches.append(1)
return dict(published)
now = [0]
cache = JwksCache(fetch, clock=lambda: now[0])
published['k2'] = 'public-key-2' # the IdP rotates
now[0] = 30
print(cache.key_for('k2'), len(fetches)) # too soon to refetch
# prints None 1
now[0] = 61
print(cache.key_for('k2'), len(fetches))
# prints public-key-2 2
print(cache.key_for('evil'), len(fetches)) # unknown kid, no refetch
# prints None 2
What to learn
- Local JWT validation with cached keys vs introspection on every request
- JWKS caching, background refresh and limiting refetches on unknown key ids
- High availability for the IdP and session store: replicas, zones and regions
- Capacity planning for login: password hashing cost, MFA, bursts at 9 a.m.
- Timeouts, circuit breakers and graceful degradation when the IdP is slow or down
Free resources
Practice
With an API validating tokens from a local Keycloak, stop Keycloak and check which requests still work (existing tokens) and which fail (login, refresh). Add JWKS caching if the API refetches keys per request. Then load-test the login endpoint and note at what rate the password hashing saturates the CPU.
Privacy, audit and compliance
Identity data is personal data. Under laws like the EU's GDPR, collect only what you need (data minimisation), say why you collect it, keep it only as long as needed, and let people see, export and delete it. Build this in from the start (data protection by design): request only the OIDC scopes and claims you use, don't copy whole IdP profiles into every service, and make account deletion actually remove or anonymise the data, including in backups on a schedule.
Security audits such as SOC 2 and ISO 27001 ask the same questions this roadmap answers, and want evidence: MFA is enforced, access is reviewed, leavers are removed promptly, admin actions are logged, logs can't be altered, and keys are rotated. Keep an append-only audit trail of who did what, separate from debug logs, with a defined retention period.
What to learn
- Data minimisation for identity: scopes, claims and which services store profile data
- Retention, deletion and anonymisation of accounts, sessions and logs
- Consent and lawful basis for optional data such as marketing or analytics
- Audit trails: tamper-evident, separate from application logs, with retention rules
- The identity controls SOC 2 and ISO 27001 auditors ask evidence for
Free resources
Practice
Make a data map for the identity part of an app: every field you store about a user, where it lives (IdP, app database, logs, analytics, backups), why you need it and how long you keep it. Delete or stop collecting one field you can't justify, and implement "delete my account" end to end.
Capstone: an end-to-end identity system
Build a small but complete system that uses most of this roadmap, then attack it. A suggested scope: a Keycloak (or other) IdP with two realms or organisations; a web app with a BFF using the authorization code flow with PKCE; a resource-server API with role- and ownership-based authorization; passkeys plus TOTP as MFA with recovery codes; a machine-to-machine job using client credentials; and SSO from a second IdP acting as a customer's company directory.
Finish with the production work: key rotation runbook, logging and alerts for the attacks in stage 14, an IdP outage test, and an ASVS level 1 check of chapters V6 to V10. Write a short README with the architecture diagram, the token table and what you would change for real traffic. Spring users can build the API and BFF with Spring Security.
What to learn
- Run an IdP with Docker and configure clients, roles, MFA and passkeys
- Build the BFF and API with code flow, PKCE, token validation and authorization checks
- Add a client-credentials job and federated SSO from a second IdP
- Rotate keys, simulate an IdP outage and check logs and alerts
- Review the system against ASVS chapters V6 to V10 and fix what fails
- Document the architecture, the tokens and the known limitations
Free resources
Practice
Ship it: put the whole system in one docker compose file, record a two-minute demo (sign in with a passkey, SSO from the second IdP, a 403 when user A requests user B's data, the nightly job's token), and publish the repository with the README. Ask someone else to try to break it.
Am I ready? Stage 16 quiz
In the backend-for-frontend pattern, what does the browser hold?
- The access token in
localStorage - The refresh token in memory
- Only an
HttpOnly session cookie for the BFF - The client secret, so it can call the IdP directly
The BFF is a confidential client that keeps all tokens server-side, so an XSS bug can't read them; the browser only has a session cookie it can't access from JavaScript.
You are rotating a JWT signing key with no downtime. What is the correct order?
- Sign with the new key, then publish it, then remove the old key
- Publish the new key, wait for JWKS caches, sign with it, remove the old key after old tokens expire
- Remove the old key, then publish and use the new one
- Publish the new key and remove the old one at the same moment
Clients must know the new public key before they see tokens signed with it, and the old key must stay until no unexpired token needs it.
The IdP is down for ten minutes. With a well-designed system, what still works?
- New logins, using a cached copy of the password database
- Nothing, because every API call checks with the IdP
- Only admin users, through a backdoor account
- Users with valid sessions or tokens keep working, because APIs validate tokens with cached keys
Local validation with cached JWKS keeps existing sessions alive; new logins and refreshes have to wait for the IdP.
An API gateway validates every token's signature and audience. What must each service still do?
- Check fine-grained permissions, such as whether this user owns this record
- Nothing, the gateway has done all the security work
- Ask the user for their password again
- Re-issue a new token for every request
The gateway can do coarse checks, but only the service knows its data. Object-level checks (no IDOR) belong in the service.