SEC/Lesson 3 of 7/7 min read
Authentication and Access Control
Authentication factors, MFA and passkeys, sessions vs tokens, JWT pitfalls, OAuth 2.0 and OpenID Connect, SSO and SAML, and access control models (DAC, MAC, RBAC, ABAC).
On this page
Authentication
Authentication verifies who someone is. Authorization decides what they may do. Authentication always comes first, and authorization must be checked on every request.
Factors
| Factor | Examples |
|---|---|
| Something you know | Password, PIN, security question |
| Something you have | Phone (TOTP app), hardware key, smart card |
| Something you are | Fingerprint, face, voice |
| Somewhere you are / something you do | Location, typing pattern (supplementary signals) |
Multi-Factor Authentication
Multi-factor authentication (MFA) requires factors from different categories. A password plus a security question is still single-factor.
Strength, weakest to strongest:
- SMS codes: vulnerable to SIM swapping and interception. Better than nothing.
- TOTP apps (Google Authenticator): a code derived from a shared secret and the current time. Can still be phished by a real-time proxy.
- Push approvals: convenient, but vulnerable to MFA fatigue (spamming prompts until the user taps approve). Use number matching.
- FIDO2 / WebAuthn hardware keys and passkeys: phishing-resistant, because the browser binds the signature to the real site's origin.
Passkey
A passkey is a WebAuthn credential: a key pair where the private key stays on the user's device (or syncs through their platform's keychain) and is unlocked with biometrics or a PIN. The server stores only the public key, so a server breach leaks nothing reusable, and a phishing site cannot get a valid signature for the real domain.
Password best practices (NIST SP 800-63B)
- Minimum length (at least 8, encourage 15+); allow long passphrases and all characters.
- Check new passwords against breached-password lists.
- No forced periodic rotation and no arbitrary composition rules; rotate only on suspected compromise.
- Rate-limit and lock out progressively on failed logins.
Credential Stuffing
Credential stuffing replays username and password pairs leaked from other breaches, betting on password reuse. Brute force tries many passwords on one account; password spraying tries a few common passwords across many accounts to dodge lockouts. Defenses: MFA, breached-password checks, rate limits, bot detection, and anomaly detection on login patterns.
Session Management
After login, the server must recognize the user on later requests.
Server-side sessions
The server stores session data and gives the browser a random session ID in a cookie.
Set-Cookie: sid=8f3a...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600HttpOnly: JavaScript cannot read it (limits XSS theft).Secure: only sent over HTTPS.SameSite: limits cross-site sending (CSRF defense).- Regenerate the session ID on login (prevents session fixation); invalidate it on logout and after idle and absolute timeouts.
Easy to revoke instantly; needs a shared session store when scaled horizontally.
JWT
A JSON Web Token is a signed, self-contained token: header.payload.signature, each part Base64URL-encoded.
{ "alg": "RS256", "typ": "JWT" }
{ "sub": "42", "role": "user", "iat": 1764400000, "exp": 1764400900 }The payload is signed, not encrypted: anyone can read it. Never put secrets in it.
Pitfalls and fixes:
| Pitfall | Fix |
|---|---|
alg: none accepted | Allow-list algorithms on the server; never trust the header's alg |
| RS256 → HS256 confusion (public key used as HMAC secret) | Pin the expected algorithm per key |
| Weak HMAC secret brute-forced offline | Use a long random secret or asymmetric keys |
| Cannot revoke before expiry | Short-lived access tokens (5 to 15 min) + revocable refresh tokens |
Token stored in localStorage stolen by XSS | Prefer HttpOnly cookies; keep XSS out |
Missing exp, aud, iss checks | Validate every claim |
| Server sessions | JWT | |
|---|---|---|
| State | On the server | In the token |
| Revocation | Instant | Hard until expiry |
| Scaling | Needs a shared store | Stateless verification |
| Best for | Traditional web apps | APIs, service-to-service, federated identity |
OAuth 2.0
OAuth 2.0 is a framework for delegated authorization: a user lets an app access their resources on another service without giving it their password ("Allow this app to read your Google Calendar").
Roles: resource owner (user), client (the app), authorization server (issues tokens), resource server (the API).
Authorization code flow with PKCE
- The client redirects the user to the authorization server with
client_id,redirect_uri,scope,state, and acode_challenge. - The user logs in and consents.
- The authorization server redirects back to
redirect_uriwith a short-lived authorization code. - The client exchanges the code (plus the
code_verifier) for an access token (and optionally a refresh token) over a back channel. - The client calls the API with
Authorization: Bearer <token>.
PKCE
PKCE (Proof Key for Code Exchange): the client makes a random code_verifier and sends its hash as code_challenge. Only the party holding the verifier can redeem the code, so a stolen code is useless. Required for mobile and single-page apps and recommended for all clients.
The state parameter prevents CSRF on the callback. Exact matching of registered redirect URIs prevents token theft via open redirects. The implicit flow (tokens in the URL fragment) is deprecated.
Other grants: client credentials (machine-to-machine, no user) and device code (TVs and CLIs).
OpenID Connect
OAuth answers "what can this app access?", not "who is the user?". OpenID Connect (OIDC) adds an authentication layer on top: an ID token (a JWT with sub, email, iss, aud, nonce) and a userinfo endpoint. "Sign in with Google" is OIDC.
Single Sign-On
Single sign-on (SSO) lets a user log in once at an identity provider (IdP: Okta, Entra ID, Google Workspace) and access many service providers without logging in again. Centralizes MFA, onboarding and offboarding.
SAML
SAML 2.0 is the older, XML-based enterprise SSO standard. The IdP sends a signed XML assertion to the service provider via the browser. Complex XML signature validation has led to many vulnerabilities (signature wrapping, comment injection); use a mature library. OIDC is the modern choice for new apps.
Access Control
Access control enforces authorization decisions.
| Model | Who decides | Example |
|---|---|---|
| DAC (discretionary) | The resource owner | Unix file permissions, sharing a Google Doc |
| MAC (mandatory) | A central policy using labels and clearances | Military classification, SELinux |
| RBAC (role-based) | Permissions assigned to roles, roles to users | admin, editor, viewer |
| ABAC (attribute-based) | Policies over user, resource and environment attributes | "Doctors can read records of their own patients during their shift" |
| ReBAC (relationship-based) | Relationships in a graph | Google Zanzibar, "editors of the parent folder" |
Role-Based Access Control
RBAC checks permissions, not role names: code asks "can this user invoice:approve?" instead of "is this user an admin?". Adding a role then never requires code changes. Watch for role explosion when roles multiply to cover every exception; ABAC handles those better.
Privilege Escalation
Privilege escalation is gaining more access than granted.
- Vertical: a normal user performs admin actions (a hidden admin endpoint with no server-side check).
- Horizontal: a user accesses another user's data at the same level, usually via IDOR (changing
/invoices/1001to/invoices/1002).
Defense: enforce authorization server-side on every request, check object ownership, deny by default, and never rely on hiding UI elements.
Quick revision
- Authentication proves identity; authorization grants access; check authz on every request.
- MFA combines factor categories; passkeys and FIDO2 keys are phishing-resistant, SMS is weakest.
- Session cookies:
HttpOnly,Secure,SameSite; regenerate on login. - JWTs are signed, not encrypted; pin the algorithm, validate claims, keep access tokens short-lived.
- OAuth 2.0 delegates authorization (use authorization code + PKCE); OIDC adds identity; SAML is legacy enterprise SSO.
- RBAC by permissions, ABAC for context rules; prevent IDOR with ownership checks.