AuthN vs AuthZ: Sessions, Tokens and Secure Login Design


System Design Phase 12: Security & Identity
Core Lesson 67 of 86 19 min read Updated Nov 30, 2026

It is 02:10 on a Saturday and the login service is pinned at 100% CPU across all 12 pods. Nothing is wrong with the code. A botnet is replaying 4,000 leaked email and password pairs per second against /login, and every attempt runs a password hash that was deliberately tuned to cost 40 ms of CPU. Real users cannot log in, and the 0.3% of guesses that succeed are quietly taking over accounts whose owners reused a password from another breach.

On Monday the incident review finds a second problem. A support engineer disabled one of the compromised accounts, but the attacker kept using it for 55 minutes, because the API accepted a signed token until it expired and nothing checked whether the account was still active.

Both failures come from the same place: treating “log the user in” as a single feature instead of a chain of separate decisions. Who is this caller? How sure are we? How do we remember that answer across requests? How do we take it back? And, separately, what is this caller allowed to do? This article walks that chain from the password field to the logout button.

What it is

Authentication (AuthN) answers “who is making this request, and how confident are we?” It ends with an identity: a user ID, a service name, a device.

Authorization (AuthZ) answers “is this identity allowed to perform this action on this resource, right now?” It ends with allow or deny.

They fail differently and they live in different places. A 401 Unauthorized response really means “I do not know who you are” (authentication failed or is missing). A 403 Forbidden means “I know who you are, and the answer is no” (authorization failed). Mixing them up in code is how you get endpoints that check that a user is logged in but never check that the invoice they are reading belongs to them, the classic insecure direct object reference.

Between the two sits session management: once a caller has authenticated, the system issues something (a session ID or a token) that stands in for the original proof on every later request. That artefact is what attackers usually steal, so most of this article is about it.

How it works

Credentials and factors

A credential is anything a caller presents to prove an identity. Factors are grouped by what they rely on:

  • Something you know: a password or PIN.
  • Something you have: a phone running an authenticator app, a hardware security key, a device holding a passkey.
  • Something you are: a fingerprint or face, almost always used locally to unlock a key on a device, never sent to the server.

Multi-factor authentication (MFA) combines two different categories. Two passwords are still one factor.

Not all second factors are equal. SMS codes are exposed to SIM swap and number porting attacks. TOTP codes from an authenticator app and push approvals are better, but both are phishable: a fake login page can relay the code to the real site in real time, and push prompts can be spammed until a tired user taps “approve”. The only widely deployed phishing-resistant option is public-key authentication bound to the website’s origin, which is what WebAuthn provides.

Storing passwords

Never store passwords, and never store a fast hash of them. SHA-256 runs billions of times per second on a GPU, so a leaked table of SHA-256 hashes is a leaked table of most passwords. Use a slow, salted, memory-hard password hashing function:

  • Argon2id is the first choice in the OWASP Password Storage Cheat Sheet. Its minimum recommended configuration is 19 MiB of memory, 2 iterations and 1 degree of parallelism (or an equivalent trade-off such as 46 MiB with 1 iteration). The memory cost is what hurts GPU and ASIC attackers.
  • scrypt is an acceptable alternative when Argon2id is not available.
  • bcrypt is fine for existing systems with a work factor of 10 or more. It silently ignores input past 72 bytes, so long passphrases or pre-pended pepper values can be truncated.
  • PBKDF2 with a high iteration count is the option when FIPS-140 validated primitives are required.

Each hash gets its own random salt, stored alongside it (the encoded Argon2id string carries it). Store the algorithm and parameters in the hash string too, so you can raise the cost later and rehash a user’s password transparently the next time they log in successfully.

Policy matters as much as the algorithm. NIST SP 800-63B revision 4 (2025) drops composition rules such as “one symbol and one digit”, drops forced periodic rotation, requires checking new passwords against lists of breached and common passwords, and sets 15 characters as the minimum when a password is the only factor. Change a password when there is evidence of compromise, not because 90 days passed.

Passkeys and WebAuthn

WebAuthn is the W3C browser API and CTAP is the protocol to external authenticators; together they form FIDO2. A passkey is a FIDO2 credential: a key pair created per site, with the private key held by the device or synced by a platform credential manager. At registration the server stores only the public key. At login the server sends a random challenge, the authenticator signs it after a local biometric or PIN check, and the server verifies the signature.

Two properties make this the strongest login available to consumers:

  1. Origin binding. The browser includes the site’s origin in the signed data, and the credential is scoped to a relying party ID such as example.com. A phishing page at examp1e.com cannot get a usable signature, no matter how convincing it looks.
  2. No shared secret. A database breach leaks public keys, which are useless to an attacker. There is nothing to stuff into other sites.

Passkeys are mainstream in 2026. Apple, Google and Microsoft platforms all create and sync them, and the FIDO Alliance estimated more than 5 billion passkeys in use worldwide in its May 2026 State of Passkeys report. The practical design today is passkeys as the primary sign-in, with a password plus a second factor as the fallback and a careful, rate-limited account recovery flow, because recovery is where attackers go once login is hard.

Remembering the login: sessions vs tokens

HTTP is stateless, so after login the server hands the client something to present on each request. There are two families.

Server-side sessions. The server generates a random, unguessable ID (at least 128 bits of entropy from a CSPRNG), stores session state keyed by it in a database or cache, and sends the ID in a cookie. Every request does a lookup. The ID itself means nothing.

Stateless tokens. The server packs the identity and an expiry into a signed token, usually a JWT, and the client sends it back. Any server holding the verification key can check it without a lookup. The token format and its pitfalls are covered in JWT architecture.

Dimension Server-side session Stateless signed token
Validation cost One store lookup per request, about 0.5 to 1 ms in-region A signature check in memory, tens of microseconds
Revocation Delete the row, effective on the next request Not possible until expiry unless you add a denylist or introspection
Data freshness Always current (roles, disabled flag) Frozen at issue time until the token is refreshed
Size on the wire 32 to 64 byte cookie Often 800 bytes to 2 KB per request
Cross-service use Every service needs the store, or a gateway resolves it Any service with the public key can verify
Operational risk Session store is a dependency on the hot path Key management and rotation become critical

The honest summary: sessions buy instant revocation and fresh data at the price of a lookup. Tokens buy local verification at the price of revocation and staleness. A session lookup in a regional Redis or Valkey cluster costs roughly the same as one network round trip inside a data centre. Use the widget to see where that sits next to a cross-region call or a disk seek.

Latency numbers, to scale

Tap a row to compare everything against it, or switch on human scale where 1 ns lasts 1 second.

Order of magnitude figures for typical 2026 server hardware and cloud networks (log scale). Exact values vary with CPU, drive model, distance and load; the ratios are what matter.

The common production answer is a hybrid. Browsers hold a session cookie. At the edge, a gateway or backend resolves the session and attaches a short-lived token (5 to 15 minutes) for internal service calls, so internal services verify locally and revocation is bounded by that short lifetime. This is the same edge-termination idea from API gateway patterns.

If the browser carries the credential in a cookie, the cookie attributes are your security boundary:

  • HttpOnly hides the cookie from JavaScript, so an XSS bug cannot read and exfiltrate it. (XSS can still make requests from the page, which is why you also need a strict Content Security Policy.)
  • Secure sends the cookie only over HTTPS.
  • SameSite controls cross-site sending. Lax sends the cookie on top-level navigations but not on cross-site subresource requests or cross-site POSTs. Strict never sends it cross-site, which breaks “click a link from email and arrive logged in”. None requires Secure and should be reserved for cookies that genuinely must work cross-site. Chromium browsers treat a missing attribute as Lax, but other browsers differ, so always set it explicitly.
  • The __Host- prefix makes the browser reject the cookie unless it is Secure, has Path=/ and has no Domain attribute. That stops a compromised or careless subdomain from planting or overwriting your session cookie.

A good default session cookie looks like this:

Set-Cookie: __Host-sid=3q2-7wTk9rL0vX4mYpB1Zg; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=28800

CSRF defenses

Cross-site request forgery works because the browser attaches cookies automatically. A page on evil.example submits a form to bank.example/transfer, and the bank’s cookie rides along. Layer these defenses:

  1. SameSite=Lax or Strict on the session cookie blocks most cross-site POSTs.
  2. Fetch Metadata and Origin checks. Modern browsers send Sec-Fetch-Site on every request. Reject state-changing requests where it is cross-site, and fall back to checking the Origin header.
  3. Anti-CSRF tokens for forms and state-changing requests: a synchronizer token stored in the session, or a signed double-submit cookie tied to the session ID.
  4. Never change state on GET. Lax deliberately lets top-level GET navigations through.

Token-in-header APIs (Authorization: Bearer ...) are not exposed to CSRF because the browser never attaches that header on its own. They are exposed to XSS instead, which is the trade the BFF pattern below avoids.

Session lifecycle: fixation, rotation, logout

Session fixation happens when an attacker gets a victim to use a session ID the attacker already knows, then waits for the victim to log in. The fix is simple: issue a brand new session ID at login, and again at any privilege change (MFA step-up, entering an admin area, password change). Never promote an anonymous session to an authenticated one in place.

Timeouts. Use an idle timeout (for example 30 minutes for a bank, days for a social app) and an absolute timeout (for example 8 to 12 hours, or 30 days with “remember me”) after which the user must authenticate again.

Logout and revocation. Logout must delete the server-side session, not just clear the cookie, because a copied cookie would otherwise keep working. “Log out of all devices” deletes every session for the user, which needs an index from user ID to session IDs. With tokens, logout means revoking the refresh token and accepting that an already-issued access token lives until it expires, or checking a denylist on every request.

The BFF pattern for browser apps

Single-page apps used to obtain OAuth tokens in the browser and keep them in localStorage. Any XSS bug then hands the attacker a bearer token they can use from anywhere. The IETF best practice for browser-based OAuth apps (published as RFC 10017, BCP 212, in August 2026) describes the Backend for Frontend (BFF) as the most secure architecture: a small server-side component owned by the app does the OAuth flow as a confidential client, keeps the access and refresh tokens server-side, and gives the browser only an HttpOnly session cookie. The browser calls the BFF; the BFF attaches the access token and forwards to APIs.

flowchart LR
B["Browser SPA"] -->|"__Host- session cookie<br/>HttpOnly, SameSite"| BFF["BFF<br/>(confidential client)"]
BFF -->|"OIDC code flow + PKCE"| IDP["Identity provider"]
BFF -->|"Bearer access token"| API1["Orders API"]
BFF -->|"Bearer access token"| API2["Profile API"]
BFF --- S["Session store<br/>tokens kept here"]
style B fill:#F1EFE8,stroke:#888780,color:#444441
style BFF fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style IDP fill:#E1F5EE,stroke:#0F6E56,color:#085041
style S fill:#FAEEDA,stroke:#854F0B,color:#633806

XSS in the SPA can still act as the user while the page is open, but it cannot steal a token to replay later, and you get server-side session revocation for free. The OAuth mechanics behind the BFF live in OAuth 2.1 and OpenID Connect.

Where authorization happens

Authentication gives you an identity. Authorization runs on every request and needs three inputs: the caller, the action and the resource. Coarse checks (is this caller allowed to call the Orders API at all, does the token have the orders:read scope) can run at the gateway. Fine-grained checks (does this order belong to this user’s organisation) need the resource, so they run in the service that owns the data, or in a policy engine that service calls. Do not trust a X-User-Id header unless the gateway strips any inbound copy and sets it itself. The models for expressing those rules, from roles to relationships, are in authorization models.

Worked example

Here is the complete login path for a web app with password plus passkey support, ending in a session cookie.

sequenceDiagram
participant B as Browser
participant A as Auth service
participant U as User DB
participant S as Session store
B->>A: POST /login (email, password, CSRF token)
A->>A: Rate limit by IP and by account
A->>U: Load user row and Argon2id hash
A->>A: Verify hash (about 40 ms CPU)
A->>B: 200 MFA required, WebAuthn challenge
B->>A: Signed assertion from passkey or security key
A->>A: Verify signature, origin, sign counter
A->>S: Create NEW session id, user, auth time, MFA flag
A->>B: Set-Cookie __Host-sid (HttpOnly, Secure, SameSite=Lax)
B->>A: GET /account with cookie
A->>S: Lookup session (about 0.5 ms)
A->>B: 200 account page

Where it breaks

Account enumeration. “No account with that email” versus “wrong password” tells an attacker which emails exist. Return the same message and, ideally, the same timing (run a dummy hash when the user does not exist). Do the same on the password reset page.

Recovery is the real login. If a passkey protects login but “forgot password” sends an SMS code that resets everything, your security level is SMS. Treat recovery as a high-risk flow: notify the user on every channel, delay sensitive actions after recovery, and require re-registration of strong factors.

Stale authorization in tokens. A token that says role: admin stays admin until it expires, even after you demote the user. Keep authorization data out of long-lived tokens, keep access tokens short, and re-check critical facts (account disabled, tenant suspended) at the service.

Revocation that is not. Clearing the cookie on logout while the server still accepts the old session ID is a common audit finding. So is a “disable user” button that does not kill sessions or refresh tokens, which is what happened in the opening incident.

Long-lived bearer tokens in the browser. Refresh tokens in localStorage turn any XSS into durable account takeover. The BFF pattern or, at minimum, sender-constrained tokens (covered in OAuth 2.1 and OpenID Connect) close that gap.

Misconception: “JWTs are more secure than sessions.” Neither is inherently more secure. A JWT is a different trade: no lookup, harder revocation. Many security problems come from picking JWTs for a single monolith that already has a database and gains nothing from stateless verification.

Misconception: “We use OAuth, so we have authentication.” Plain OAuth gives you an access token for an API, not a verified login. Login needs OpenID Connect and its ID token. The next article covers why that difference has caused real breaches.

Real-world systems

  • Browsers and platforms: Chrome, Safari, Firefox and Edge implement WebAuthn. iOS, macOS, Android and Windows create passkeys, and Apple, Google and Microsoft sync them through their credential managers, as do third-party managers such as 1Password and Bitwarden.
  • Frameworks: Django, Rails and Laravel default to server-side session handling with CSRF protection built in. Spring Security supports both sessions and OAuth resource server token validation.
  • Password hashing libraries: libsodium and the reference argon2 library implement Argon2id; most languages also ship mature bcrypt bindings.
  • Session stores: Redis and Valkey are the usual session stores, with key expiry handling idle timeouts. Note that Redis 8 is AGPL licensed, and Valkey is the Linux Foundation fork under BSD.
  • Identity providers: Auth0, Okta, Microsoft Entra ID, Amazon Cognito, Keycloak and Supabase Auth all offer hosted login, MFA and passkeys, which is usually a better choice than building this yourself.

How to apply it

Defaults for a new product in 2026:

  1. Buy or adopt before you build. Use a mature identity provider or framework. Write the authorization logic yourself; delegate the login ceremony.
  2. Passkeys first, password plus TOTP or security key as fallback, SMS only as a last resort.
  3. Argon2id at OWASP parameters or stronger, parameters stored in the hash, rehash on login when you raise the cost.
  4. Browser apps get a server-side session cookie with __Host-, Secure, HttpOnly, SameSite=Lax, through a BFF if the frontend is an SPA.
  5. Rotate the session ID at login and at every privilege change. Idle and absolute timeouts.
  6. Logout deletes server state. “Log out everywhere” exists and works.
  7. Internal services get short-lived tokens minted at the edge, 5 to 15 minutes.
  8. Authorization runs per request, next to the data, with 401 and 403 used correctly.
Situation Choose
Monolith or few services, browser clients Server-side sessions
SPA talking to your own APIs BFF with session cookie
Many internal services, need local verification Edge session, short-lived internal tokens
Third-party apps acting for your users OAuth 2.1 access tokens
Mobile app OAuth code flow with PKCE, tokens in the OS keystore

Interview questions

Q1: Design login for a web app and its mobile app. What do you store, and what does each client hold?

Model answer: Use a hosted identity provider or a well-tested framework for the login ceremony. Support passkeys as the primary method and password plus a second factor as the fallback. Passwords are stored as Argon2id hashes with a per-user salt and OWASP-level parameters, checked against breached-password lists at registration. Put per-IP and per-account rate limits and a concurrency cap in front of hashing. The web app gets a server-side session: a random 128-bit or larger ID in a __Host- cookie with Secure, HttpOnly and SameSite=Lax, a new ID issued at login and at step-up, CSRF protection on state-changing requests, and idle plus absolute timeouts. If the web frontend is an SPA, a BFF holds any OAuth tokens. The mobile app uses the OAuth authorization code flow with PKCE through the system browser and stores its refresh token in the OS keystore, with refresh token rotation. Logout deletes server-side sessions and revokes refresh tokens.

Q2: A user reports their account was hijacked. How do you kill every active login immediately?

Model answer: With server-side sessions, keep an index from user ID to session IDs and delete them all; the next request from any device fails. Revoke all refresh tokens for the user at the authorization server. For any self-contained access tokens already issued, either accept exposure up to their lifetime (which is why they should be 5 to 15 minutes) or publish a per-user “tokens issued before time T are invalid” marker that services check, which means a lookup on every request, cached briefly. Then force re-authentication with a strong factor, review and remove attacker-registered passkeys or MFA devices, and notify the user. Disabling the account must trigger the same revocation, not just set a flag.

Q3: Why can’t you rely on SameSite cookies alone for CSRF protection?

Model answer: SameSite is defined by site (registrable domain), not origin, so a vulnerable sibling subdomain counts as same-site and can forge requests. Lax allows top-level GET navigations, so any state change on GET is still exposed. Defaults differ between browsers when the attribute is missing, and some legitimate flows need SameSite=None. So treat SameSite as one layer and add Fetch Metadata or Origin checks plus anti-CSRF tokens for state-changing requests, and never mutate state on GET.

✅ Key takeaways

  • Authentication establishes identity (401 when it fails); authorization decides each action on each resource (403 when it fails). Keep them separate in code.
  • Store passwords with Argon2id at OWASP parameters, rate limit before hashing, and make passkeys the primary login because they are phishing resistant and leak nothing useful in a breach.
  • Server-side sessions trade one sub-millisecond lookup for instant revocation and fresh data; stateless tokens trade revocation for local verification. Most systems use both, at different layers.
  • Session cookies need __Host-, Secure, HttpOnly and an explicit SameSite, plus CSRF defenses, a new session ID at login, and server-side deletion on logout.
  • For SPAs, the BFF pattern keeps tokens off the browser entirely and is the current IETF recommendation.

🧠 Check your understanding

0 / 4
  1. 1An API returns a response when a logged-in user requests an invoice owned by a different customer. Which control is missing?

  2. 2Why is Argon2id preferred over SHA-256 with a salt for password storage?

  3. 3Your SPA keeps a refresh token in localStorage. What is the strongest fix?

  4. 4What does issuing a new session ID at login protect against?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.