Authentication vs Authorization
| Aspect | Authentication (AuthN) | Authorization (AuthZ) |
|---|---|---|
| Question it answers | Who are you? (Prove your identity) | What are you allowed to do? (Permissions) |
| Happens | First – before anything else | Second – after identity is proven |
| Analogy | Showing your passport/ID at airport security | After passport check, being allowed into VIP lounge or not |
| Real-world example | Logging into Gmail with password/Google Authenticator | After login, you can read your emails but not delete others’ |
| Technical output | You get a session, JWT, ID token, cookie | You get scopes, roles, permissions, claims |
| Protocol/Standard | OpenID Connect, SAML, WebAuthn, LDAP, Kerberos | OAuth 2.0 scopes, RBAC, ABAC, ReBAC, Open Policy Agent (OPA) |
| Can change during session | Usually not (you are Alice the whole session) | Yes – permissions can be revoked or upgraded anytime |
| Failure message | “Invalid username or password”, “MFA failed” | “403 Forbidden”, “Access denied”, “Insufficient privileges” |
Authentication (AuthN) – Proving Who You Are
Goal: Verify identity
Common methods (2025):
- Password + MFA (TOTP, WebAuthn, Push)
- Passkeys (FIDO2 – passwordless)
- Social login (Login with Google → OIDC)
- Magic links / OTP via email/SMS
- Biometrics (Face ID, fingerprint)
Result after success:
- You receive an ID Token (JWT) saying sub: "user_123", name: "Alice"
- A session cookie is set
- You are now a principal in the system
Stateful Authentication
- Definition: The server maintains session state (e.g., user ID, roles) for each authenticated user, typically stored in server-side memory, database, or cache (e.g., Redis). The client receives an opaque identifier (session ID) to reference this state.
- Mechanics:
- User logs in (e.g., username/password).
- Server validates credentials, creates session data (e.g.,
{user_id: 123, roles: ['admin']}), stores it (e.g., Redis keysession:abc123= data). - Server sets cookie (e.g.,
Set-Cookie: session_id=abc123; HttpOnly; Secure). - On subsequent requests, client sends cookie; server looks up session ID, retrieves state, and validates (e.g., expiry, IP binding).
- Logout: Server deletes session data.
- Advantages:
- Easy Revocation: Delete session instantly (e.g., global logout).
- Rich State: Store complex data (e.g., cart items) without client bloat.
- Security: Server controls; hard to forge.
- Disadvantages:
- Scalability Issues: Requires shared state (sticky sessions or central store); horizontal scaling needs replication.
- State Overhead: Memory/DB load; sessions expire if not cleaned.
- Use Cases: Traditional web apps (e.g., e-commerce with server-side carts); banking (instant revocation).
- 2025 Trends: Declining for APIs; used with short sessions + rotation.
Stateless Authentication
- Definition: The server does not store session state; all necessary info is embedded in a self-contained token (e.g., JWT) sent by the client. Server validates the token locally without lookups.
- Mechanics:
- User logs in; server issues token (e.g., JWT signed with private key, containing claims like
user_id,exp). - Client stores token (e.g., localStorage or secure cookie).
- On requests, client includes token (e.g.,
Authorization: Bearer <jwt>). - Server verifies signature, claims (e.g., expiry, issuer); no DB query.
- Logout: Client discards token; server can't revoke mid-use (use short expiry or blacklist).
- Advantages:
- Scalability: Stateless—any server validates independently; easy horizontal scaling.
- Performance: No DB/network calls per request.
- Decentralized: Works offline (for cached tokens).
- Disadvantages:
- Revocation Hard: Can't invalidate until expiry; needs blacklist (stateful) or short lives.
- Token Bloat: Larger payloads (1-3KB); claims exposed (use encryption for sensitive).
- Use Cases: Microservices/APIs (e.g., REST/GraphQL); SPAs/mobile (JWT in headers).
- 2025 Trends: Dominant for APIs; hybrid with refresh tokens for revocation.
Comparison Table: | Aspect | Stateful | Stateless | |--------|----------|-----------| | State Location | Server (DB/Redis) | Client token | | Revocation | Instant | Expiry/blacklist | | Scalability | Needs shared state | Infinite horizontal | | Latency | Higher (lookup) | Lower (local verify) | | Security | Stronger control | Depends on token strength |
Single Sign-On (SSO)
Definition
SSO is an authentication method allowing users to log in once and access multiple applications/resources without re-entering credentials. It centralizes identity verification, reducing friction and improving security (fewer passwords).
Mechanics
- Core Flow (SAML/OIDC-based):
- User accesses App A (Identity Provider - IdP client).
- If unauthenticated, redirect to IdP (e.g., Okta, Azure AD).
- User authenticates at IdP (password/MFA).
- IdP issues token/assertion to App A.
- App A grants access; user visits App B.
- App B checks IdP (via token or session); IdP confirms (cached or re-validate).
- Federation: IdP trusts Service Providers (SPs); uses standards like SAML (XML) or OIDC (JWT).
- Session Management: IdP maintains central session; SPs validate via artifacts/tokens.
Advantages
- User Experience: Seamless (one login).
- Security: Central MFA/password policy; audit logs.
- Admin Efficiency: Single user directory.
Disadvantages
- Single Point of Failure: IdP downtime affects all.
- Complexity: Federation setup (trust, token validation).
- Privacy: IdP sees all access.
Standards & Flows
- SAML 2.0: Enterprise SSO (XML assertions).
- OIDC: Modern web SSO (JWT ID tokens).
- CAS (Central Authentication Service): University-style.
Use Cases: Enterprise (Okta SSO for Office/Google Workspace); web portals.
Multi-Factor Authentication (MFA / 2FA)
Definition
MFA (Multi-Factor Authentication) requires multiple verification methods from different categories to confirm identity, enhancing security beyond passwords. 2FA is MFA with two factors.
Factors (Something You...)
| Factor | Examples | How It Works |
|---|---|---|
| Knowledge | Password, PIN | User-entered secret. |
| Possession | SMS OTP, TOTP app (Google Authenticator), hardware token (YubiKey) | Time-based or one-time codes. |
| Inherence | Biometrics (fingerprint, face ID), behavioral (keystroke dynamics) | Device sensor-based. |
| Location/Time | Geofencing, risk-based | Contextual (e.g., unusual IP → extra step). |
Mechanics
- Primary Auth: Username/password.
- Secondary Challenge: IdP sends factor (e.g., TOTP code via app).
- Verification: User submits; IdP validates (e.g., HMAC-based OTP).
- Success: Issue token/session.
Types of MFA
- TOTP (Time-Based OTP): HMAC-SHA1 with time counter (RFC 6238).
- HOTP (HMAC-Based OTP): Counter-based (RFC 4226).
- Push Notifications: App push with approve/deny (e.g., Duo).
- FIDO2/WebAuthn: Passwordless (hardware-bound keys).
Advantages
- Security: Mitigates phishing (can't guess OTP).
- Compliance: Required for GDPR, PCI-DSS.
Disadvantages
- UX Friction: Extra steps.
- Dependency: Lost phone = locked out.
Use Cases: Banking logins, corporate VPN.
Passwordless & Passkeys (WebAuthn, FIDO2)
Definition
Passwordless authentication eliminates passwords using biometrics, hardware tokens, or magic links, relying on public-key cryptography for secure, phishing-resistant logins. Passkeys are FIDO2-based credentials stored on devices (e.g., iPhone Secure Enclave).
Mechanics (FIDO2/WebAuthn Flow)
- Registration: User creates credential; RP (Relying Party) sends challenge; authenticator (device) generates key pair, signs challenge with private key, sends public key + attestation to RP.
- Authentication: RP sends challenge; authenticator signs with private key; RP verifies signature with public key.
- Success: RP issues session/token.
FIDO2 Components
- WebAuthn: W3C API for browsers (e.g.,
navigator.credentials.create()). - CTAP: Client to Authenticator Protocol (USB/NFC/Bluetooth).
Advantages
- Phishing-Resistant: Challenge bound to domain.
- Convenient: Biometrics (no passwords).
- Secure: Private key never leaves device.
Disadvantages
- Device Dependency: Lost device = recovery needed.
- Adoption: Requires app/browser support.
Use Cases: Apple Passkeys, Google Passwordless, Microsoft Authenticator.
2025 Status: Passkeys are mainstream (90%+ adoption in iOS/Android); passwords are legacy.
Authorization (AuthZ) – Deciding What You Can Do
Goal: Enforce policy based on identity
Runs after authentication is successful
Common models:
| Model | How it works | Example |
|------------|--------------------------------------------------|-------|
| RBAC | Role-Based Access Control (user → roles → permissions) | User has role “admin” → can delete users |
| ABAC | Attribute-Based (rules on user, resource, context) | If user.department == resource.owner_department → allow |
| ReBAC | Relationship-Based (Google Zanzibar style) | User is “editor” of Document X → can edit |
| Scopes | OAuth/OIDC scopes | scope: read:emails write:calendar |
Key Mistakes Developers Make | Mistake | Correct Understanding | |----------------------------------------|---------------------------------------------------------| | Thinking OAuth 2.0 = login | OAuth 2.0 = authorization; OIDC = login | | Storing permissions in JWT access token| Fine if short-lived & signed; dangerous if long-lived | | Skipping authorization after auth | “Anyone logged in can do anything” → disaster | | Using authentication tokens for authZ | ID token ≠ permission token |
Identity, Principal, Subject and Claims
| Term | Meaning | Where you see it | Typical value example |
|---|---|---|---|
| Identity | The real-world entity (human, service, device, organization) you are talking about | Everywhere in identity systems | "Alice Smith", "API Service #42" |
| Principal | The authenticated entity that is currently acting in the system | Code, logs, audit trails | Authenticated user or service account |
| Subject | The unique, immutable identifier of the principal inside an identity provider (IdP) | JWT sub claim, SAML NameID, session ID |
"248289761001", "user_abc123" |
| Claims | Key-value statements/assertions about the subject (issued by a trusted authority) | Inside ID Token, Access Token, SAML Assertion | {"sub": "248289761001", "email": "alice@company.com", "role": ["admin"], "department": "eng"} |
- Identity → real person/service
- → gets authenticated → becomes Principal
- → identified by a unique Subject (
sub) - → described by Claims (name, email, roles, etc.)
Most common place you see all four together
// OIDC ID Token (JWT payload)
{
"iss": "https://auth.company.com", // who issued
"sub": "248289761001", // Subject = unique ID of the principal
"name": "Alice Smith", // Claims
"email": "alice@company.com", // Claims
"role": ["admin", "engineer"] // Claims
}
Here: Alice (Identity) is the current Principal, identified by subject 248289761001, and has the listed claims.
Token Types & Security
Opaque Tokens
- Definition: Random, high-entropy strings (e.g.,
a7f3c4e8b9d2e1f0...) issued by the authorization server (AS). They are meaningless to clients and serve as references to server-side state. - How They Work: Client sends token to resource server (RS); RS introspects (queries AS via
/token/introspectendpoint) to validate and retrieve claims (e.g., scopes, user ID). - Storage: Typically in HTTP headers (
Authorization: Bearer <opaque>). - Pros:
- High Security: No embedded info; revocation easy (delete from DB/Redis); smaller size (~32-64 bytes).
- Flexibility: AS controls all state; supports dynamic updates (e.g., revoke without client changes).
- Privacy: No sensitive claims leaked if intercepted.
- Cons:
- Stateful: AS/RS must share state (e.g., Redis); scales poorly without distributed storage.
- Latency: Each validation requires RS-AS round-trip (adds 50-200ms).
- Dependency: RS offline if AS is down.
JWTs (JSON Web Tokens)
- Definition: Self-contained, signed tokens (Base64(Header).Base64(Payload).Signature) encoding claims (e.g., user ID, scopes) in JSON format. RS validates locally using public key/JWKS.
- How They Work: Client sends JWT; RS verifies signature (e.g., RS256 with RS public key) and claims (e.g.,
exp,aud). - Storage: Same as opaque (Bearer header).
- Pros:
- Stateless: RS validates offline (no AS call); scales horizontally.
- Rich Claims: Embeds data (e.g., roles); customizable.
- Efficiency: Single round-trip; fast with caching.
- Cons:
- Larger Size: 1-3KB (Base64 overhead); bloat in headers.
- Revocation Hard: Can't revoke mid-lifetime (use short expiry or blacklist).
- Security Risks: If signing key leaks, forgery possible; claims exposed (use JWE for encryption).
Comparison Table: | Aspect | Opaque Tokens | JWTs | |--------|---------------|------| | State | Stateful (server lookup) | Stateless (self-validating) | | Size | Small | Larger | | Revocation | Easy (DB delete) | Hard (blacklist/short expiry) | | Performance | Slower (network call) | Faster (local verify) | | Best For | Sensitive/high-security | Scalable APIs/microservices |
2025 Trend: Hybrid—opaque for sensitive, JWT for performance.
Access Token
- Definition: Short-lived bearer token granting scoped access to resources (e.g., "read:profile").
- Purpose: Authorizes API calls (sent to RS in
Authorization: Bearer <token>). - Structure: Opaque string or JWT; claims include scopes, expiry (
exp), audience (aud). - Lifetime: 5-60 minutes.
- Validation: RS introspects (opaque) or verifies signature (JWT).
Refresh Token
Long-lived token used to obtain new access tokens without re-authentication.
- Purpose: Extends sessions securely (avoids repeated logins).
- Structure: Opaque (preferred) or JWT; no scopes (just renewal).
- Lifetime: Hours to days/weeks.
- Usage: Client POST to AS
/tokenwithgrant_type=refresh_token&refresh_token=<token>. - Security: Rotate on use (invalidate old); store securely.
Refresh tokens enable long sessions without re-login but risk compromise if stolen. Rotation and reuse detection mitigate this by invalidating old tokens.
Refresh Token Rotation
- Definition: On each use, AS issues a new refresh token and invalidates the old one.
- How It Works:
1. Client sends old refresh token to /token.
2. AS validates, issues new access + new refresh token.
3. Client discards old refresh.
- Benefits: Limits damage (stolen token usable once); detects compromise (reuse of old invalidates).
- Implementation: AS tracks per-client (e.g., Redis: SET client_id:refresh <token_hash> EX 86400; on use, check/match and set new).
Reuse Detection - Definition: AS detects if a refresh token is reused (e.g., stolen and used elsewhere), invalidating the session. - How It Works: 1. Rotation + device fingerprint (e.g., user-agent hash). 2. On reuse: AS sees mismatch (e.g., different IP/device) → revoke all tokens for user. - Advanced: Token binding (e.g., to TLS session ID) or pairwise (client-AS shared secret).
Pros: Proactive security. Cons: Adds state (AS tracks tokens); client must handle rotation.
Rotation mandatory for sensitive apps (RFC 6819); reuse triggers alerts (e.g., Okta).
ID Token
- Definition: JWT issued by OIDC provider with user identity claims (e.g.,
sub,name,email). - Purpose: Proves authentication (who the user is); not for authorization (no scopes).
- Structure: JWT with OIDC claims (
iss,aud,sub,iat,exp,noncefor replay protection). - Lifetime: Same as access token (5-60min).
- Validation: Client verifies signature/claims; used for UI (e.g., display name).
Comparison Table: | Token | Purpose | Structure | Claims | Used By | Lifetime | |-------|---------|-----------|--------|---------|----------| | Access | Authorization (API access) | Opaque/JWT | Scopes, aud | RS | Short | | Refresh | Renew access | Opaque/JWT | Minimal | AS | Long | | ID | Authentication (user info) | JWT | Identity (sub, name) | Client | Short |
Nuance: ID token for client (IDP verification); access for RS (scope enforcement).
DPoP (Demonstrating Proof-of-Possession)
DPoP is an OAuth extension (RFC 9449, 2023) turning bearer tokens into proof-of-possession tokens by requiring clients to demonstrate key ownership per request.
Core Mechanics
- Key Pair: Client generates asymmetric keys (e.g., ES256); sends public thumbprint (
jkt) to AS during token issuance. - Token Binding: AS embeds
cnf: {"jkt": "<thumbprint>"}in access token. - Proof Generation: Client creates short-lived DPoP JWT:
- Claims:
htm(HTTP method),htu(full URL),jkt(matches token),iat(timestamp). - Signed with private key.
- Request Flow: Client includes
DPoP: <dpop_jwt>header alongsideAuthorization: Bearer <token>. - Server Validation:
- Verify DPoP signature with token's
cnf.jkt. - Check
htm/htumatch request. - Ensure
iatfresh (e.g., <5min). - Replay Prevention: Unique
jti+ nonce; server tracks briefly.
Pros: Bearer-like simplicity with PoP security; no certs. Cons: Signing overhead; key management.
2025 Use: Standard in FAPI (financial APIs); emerging in general OAuth.
Sender-Constrained Tokens (mTLS, DPoP)
Sender-constrained tokens bind an access token to a specific client (via key/cert), preventing use by others even if stolen—unlike bearer tokens.
General Mechanism
- Binding: Token includes
cnfclaim with proof (e.g., key thumbprint). - Proof: Client provides cryptographic evidence (e.g., signature) per request.
mTLS (Mutual TLS)
- How: Client presents X.509 cert during TLS handshake; token's
cnf.x5t#S256matches cert thumbprint. - Flow: TLS handshake authenticates client; HTTP layer uses token with matching
cnf. - Pros: Strong (cert-based); no per-request overhead. Cons: Cert management.
DPoP (Demonstrating Proof-of-Possession)
- How: Client generates ephemeral key pair; token
cnf.jkt= public key thumbprint. Per request, client sends DPoP proof (JWT signed with private key) inDPoPheader. - Flow: 1. Client keys → AS includes
cnfin token. 2. Request:Authorization: Bearer <token>+DPoP: <proof_jwt>. 3. RS verifies proof matches token'scnf. - Pros: Lightweight; works over HTTP. Cons: Per-request signing overhead.
Comparison: mTLS = TLS-layer constraint; DPoP = HTTP-layer (RFC 9449, FAPI standard).
Token Revocation & Introspection (RFC 7009)
Token revocation invalidates issued tokens before expiry; introspection queries AS for status.
Revocation (RFC 7009)
- How: Client/AS POST to
/revokewithtoken(access/refresh),token_type_hint(access_token/refresh_token),client_id/secret. - Response: 200 OK (revoked) or 400 (invalid).
- Mechanics: AS adds to blacklist (Redis) or marks in DB.
- Use: Logout, compromise detection.
Introspection (RFC 7662)
- How: RS POST to AS
/introspectwithtoken,client_id/secret. - Response: JSON with
active: true/false, claims (e.g.,scope,exp). - Mechanics: AS checks DB/blacklist; returns subset of original claims.
- Use: For opaque tokens; RS validates without decoding.
Pros: Centralized control. Cons: Stateful (AS load); network call per validation.
2025 Standard: Mandatory for opaque tokens; JWTs use local validation + introspection for revocation.
Token Storage Best Practices
Secure storage prevents theft (XSS, MITM); choose based on client type.
HttpOnly, Secure, SameSite Cookies
- HttpOnly: Prevents JS access (blocks XSS theft).
- Secure: HTTPS-only (blocks HTTP interception).
- SameSite: Restricts cross-site requests (Lax/Strict/None; Lax for safe methods).
- How: Server sets:
Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Lax. - Best For: Web apps (server-side sessions/tokens).
In-Memory Storage
- How: Store in JS variable/memory (e.g.,
localStorageavoided). - Pros: Fast access. Cons: Lost on page refresh; vulnerable to XSS.
- Best For: SPAs with short sessions (pair with HttpOnly for critical).
Secure Storage (Mobile/Native)
- iOS: Keychain Services (encrypted, sandboxed).
- Android: Keystore (hardware-backed).
- Desktop: OS keyring (Windows Credential Manager, macOS Keychain).
- How: Use platform APIs (e.g.,
KeychainAccessin Swift). - Best For: Native apps (tokens never leave device).
Overall Best Practices: - Web: HttpOnly/Secure/SameSite cookies for tokens. - SPA/Mobile: In-memory + secure storage; avoid localStorage (XSS risk). - Rotation: Refresh proactively (e.g., 80% expiry). - HTTPS: Always (HSTS for enforcement).
Nuance: No storage is foolproof—use short expiry + rotation.
OpenID Connect (OIDC)
OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0, designed for authentication (verifying who a user is) and providing standardized, secure ways to obtain user information. It extends OAuth's authorization framework to include identity verification via JSON Web Tokens (JWTs). As of 2025, OIDC 1.0 with extensions (e.g., OIDC Core 1.0 Errata) remains the standard, supporting modern use cases like SSO (Single Sign-On), federated identity, and API access. OIDC is not a replacement for OAuth but adds authentication on top, enabling "login with Google" flows.
OIDC Flows (Authorization Grant Types) OIDC uses OAuth flows with added ID tokens. Primary flows:
1. Authorization Code Flow (Recommended)
- Use: Server-side apps (secure code exchange).
- Steps:
- Client redirects user:
GET /authorize?client_id=abc&response_type=code&scope=openid profile&redirect_uri=cb&state=xyz. - User authenticates/consents at OpenID Provider (OP).
- OP redirects:
cb?code=def&state=xyz(state prevents CSRF). - Client POST to
/token:code=def&client_id=abc&client_secret=secret&redirect_uri=cb. - OP responds:
{access_token: "...", id_token: "...", refresh_token: "..."}. - Client validates ID token (signature, claims); uses access token for APIs.
- PKCE Extension: For public clients (mobile/SPA); adds
code_challengeto prevent interception. - Pros: Secure (code not exposed). Cons: Requires backend.
2. Implicit Flow (Deprecated in OAuth 2.1)
- Use: Client-side apps (SPA); tokens returned directly in redirect.
- Steps: Similar to Authorization Code, but
response_type=id_tokenortoken id_token; tokens in URL fragment (#id_token=...). - Pros: No backend. Cons: Tokens exposed in browser; vulnerable to interception.
3. Hybrid Flow
- Use: Combines code + tokens in redirect for immediate use.
- Steps:
response_type=code id_token; gets code + ID token upfront.
4. Client Credentials Flow
- Use: Machine-to-machine (no user); client authenticates with credentials.
- Steps: Client POST to
/tokenwithclient_id/secretandgrant_type=client_credentials. - Response: Access token (no ID token, as no user).
5. Device Authorization Flow
- Use: Devices without browsers (e.g., smart TV).
- Steps: Device polls
/tokenwith device/user code; user enters code on another device to authorize.
Nuance: Authorization Code + PKCE is the secure default for all clients.
Security Considerations
- JWT Validation: Verify signature (JWKS), expiry (
exp), issuer (iss), audience (aud). - Token Storage: HttpOnly/Secure cookies for web; secure storage for mobile (Keychain/Keystore).
- Threats: Token theft (use short expiry, PKCE); replay (nonce/JTI claims).
- Scopes: Minimal (
openidfor auth only). - Compliance: OIDC for SSO; FAPI for financial-grade (enhanced security).
Implementation Overview
- Libraries: oidc-client-js (JS), Auth0 SDK, Spring Security OAuth.
- Flows in Code (Python with Authlib): ```python from authlib.integrations.requests_client import OAuth2Session
client = OAuth2Session(
client_id='abc',
client_secret='secret',
redirect_uri='http://localhost/cb',
scope=['openid', 'profile']
)
authorization_url, state = client.create_authorization_url('https://op.example.com/authorize')
# Redirect user to authorization_url
# After callback:
token = client.fetch_token('https://op.example.com/token', authorization_response=cb_url)
user_info = client.get('https://op.example.com/userinfo').json() # Claims
``
- **ID Token Validation**:jwt.decode(token, jwks_key, algorithms=['RS256'])`.
OIDC streamlines secure authentication atop OAuth. For code demos or PKCE details, let me know!
Production and Operations
Token Revocation Lists vs Short Expiry
Token Revocation Lists
- Definition: A server-side blacklist (e.g., Redis set or DB table) storing invalidated tokens before their expiry, enabling immediate revocation.
- Mechanics:
- On logout/compromise, add token ID (
jticlaim) to list with TTL (expiry time). - On validation: RS/AS checks list (e.g., Redis
SISMEMBER blacklist <jti>); if present, reject. - Cleanup: Auto-expire entries to avoid growth.
- Pros:
- Immediate Effect: Revoke mid-lifetime (e.g., logout from all devices).
- Granular: Per-token/user/session.
- Cons:
- Stateful Overhead: Requires distributed storage (Redis cluster); scales poorly for billions of tokens.
- Consistency: Eventual (race conditions during add/check).
- Use Cases: Global logout (e.g., banking); compromised device detection.
- 2025 Best Practice: Use for JWTs (
jticlaim); combine with short expiry to limit list size.
Short Expiry
- Definition: Issuing tokens with brief lifetimes (e.g., 15min for access tokens), forcing frequent renewal via refresh tokens.
- Mechanics:
- Set low
expclaim (Unix timestamp). - Client refreshes proactively (e.g., at 80% expiry) using refresh token.
- On expiry, token auto-invalidates—no list needed.
- Pros:
- Stateless Simplicity: No server storage; scales infinitely.
- Narrow Attack Window: Stolen token usable only briefly.
- Cons:
- Frequent Renewals: Increases AS load; UX disruption if refresh fails.
- No Instant Revoke: Can't invalidate until expiry (unless list hybrid).
- Use Cases: Stateless APIs (microservices); mobile apps with background refresh.
- 2025 Best Practice: Access: 5-15min; refresh: 24h with rotation. Pair with silent renew (JS SDKs).
Comparison Table: | Aspect | Revocation Lists | Short Expiry | |--------|------------------|--------------| | Revocation Speed | Instant | At expiry | | State | Stateful (storage) | Stateless | | Scalability | Limited (list size) | Infinite | | Overhead | Storage/query | Renewal calls |
Hybrid: Short expiry + lists for critical revocations.
Secure Password Hashing (Argon2, bcrypt, scrypt, PBKDF2)
Password hashing transforms plaintext passwords into fixed-length strings using slow, one-way functions to resist brute-force attacks. Never store plaintext—use salted hashes.
Core Principles
- One-Way: Irreversible (no decryption).
- Salt: Random per-user value to prevent rainbow tables.
- Work Factor: Computational cost (e.g., iterations) to slow attacks.
- Pepper: Global secret (stored outside DB) for extra security.
Algorithms
| Algorithm | Basis | Pros | Cons | Cost Parameter | Use Case |
|---|---|---|---|---|---|
| PBKDF2 (RFC 2898) | PRF (HMAC-SHA256) iterations | Mature, flexible. | Slower on GPU. | Iterations (e.g., 310,000). | Legacy systems. |
| bcrypt | Blowfish cipher + salt. | GPU-resistant; adaptive cost. | Fixed 4KB limit. | Cost (e.g., 12 = 2^12 rounds). | Web apps (Django default). |
| scrypt | PBKDF2 + memory-hard (SMix). | Memory-intensive (anti-ASIC). | High RAM use. | N (memory), r (block), p (parallel). | Password managers. |
| Argon2 (2015 winner) | Blake2b + memory-hard lanes. | Best resistance (time/memory/parallel). | Variants for needs. | Memory (e.g., 64MiB), iterations, parallelism. | Modern (OWASP recommended). |
Mechanics (Argon2 Example)
- Input: Password + salt (random 16-32 bytes).
- Derive Key: Run Argon2 with params (memory=64MiB, iterations=3, parallelism=4).
- Output: 32-byte hash (e.g.,
$argon2id$v=19$m=65536,t=3,p=4$...). - Verification: Re-hash input with stored salt/params; compare outputs.
Python Example (Argon2):
from argon2 import PasswordHasher
ph = PasswordHasher()
hashed = ph.hash("password") # Salt auto-generated
print(hashed) # $argon2id$v=19$m=65536,t=3,p=4$...
if ph.verify(hashed, "password"): # True
print("Valid")
Best Practices: Argon2id (hybrid); cost tuned for 0.1-1s hash time; unique salts; pepper for DB breach protection.
Secure Session Management
Session management securely tracks authenticated user state across requests, balancing usability and security.
Core Mechanics
- Session ID: Opaque, random string (e.g., 128-bit) as key to server-side data.
- Storage: Server-side (memory/Redis/DB); client-side cookie references it.
- Lifecycle: Create on login; expire on timeout/logout; regenerate ID periodically.
Best Practices
- Secure Cookies: HttpOnly (no JS access), Secure (HTTPS-only), SameSite=Lax/Strict (CSRF protection).
- ID Generation: Cryptographically secure random (e.g.,
secrets.token_urlsafe(32)in Python). - Binding: Tie to IP/user-agent (detect hijacking).
- Expiry: Sliding (extend on activity) or absolute; idle timeout (30min).
- Regeneration: On privilege change (e.g., login → admin).
- Storage: Redis for scale (TTL auto-expiry); encrypt sensitive data.
Python (Flask) Example:
from flask import Flask, session, request
app = Flask(__name__)
app.secret_key = 'strong-secret-key'
@app.route('/login')
def login():
session['user_id'] = 123 # Server-side storage
session.permanent = True # Persistent cookie
return 'Logged in'
@app.route('/profile')
def profile():
if 'user_id' not in session:
return 'Unauthorized', 401
return f'User {session["user_id"]}'
- Config:
session.permanent = True; regeneratesecret_key.
Threats Mitigated: Session fixation (regenerate ID), hijacking (binding/expiry).
Logout – Front-Channel vs Back-Channel (OIDC RP-Initiated Logout, Session Management)
Logout terminates sessions securely, especially in SSO (OIDC/SAML) to prevent orphaned access.
Front-Channel Logout
- Definition: Client-side notification (e.g., redirect to IdP logout endpoint) to end user session at IdP and SPs (Service Providers).
- Mechanics (OIDC RP-Initiated):
- RP (Relying Party, e.g., your app) detects logout.
- Redirect user to IdP
/logoutwithid_token_hint(JWT to identify session) andpost_logout_redirect_uri. - IdP logs out user (clears central session) and redirects to RP's URI.
- RP clears local session/cookie.
- Pros: User-visible; ends all SSO sessions. Cons: Requires user action; network-dependent.
Back-Channel Logout
- Definition: Server-to-server notification (direct RP-IdP communication) to end sessions without user involvement.
- Mechanics (OIDC Back-Channel):
- IdP detects global logout (e.g., user logs out from another SP).
- IdP POSTs to RP's
/logoutendpoint withlogout_token(JWT containing session details, signed by IdP). - RP validates token, clears local session for the user.
- Pros: Instant, no user redirect. Cons: Requires RP endpoint; polling for notifications.
Session Management in OIDC
- Front-Channel Logout Session: Uses
session_stateparam in redirect to correlate (prevents CSRF). - Back-Channel: Relies on
sidclaim in logout_token for session ID. - Best Practices: Implement both; use iframe for front-channel in SPAs (silent logout).
Comparison Table: | Aspect | Front-Channel | Back-Channel | |--------|---------------|--------------| | Initiation | User/RP redirect | IdP → RP direct | | User Involvement | Yes (browser redirect) | No | | Reliability | Network-dependent | Server-to-server | | Use Case | User-initiated logout | Global session end |
2025 Standard: OIDC RP-Initiated Logout (RFC 7009) for front; Back-Channel (RFC 7967) for seamless.
SSL/TLS Certificates: Securing Client-Server Interactions
SSL (Secure Sockets Layer) and TLS (Transport Layer Security) certificates are digital certificates that enable encrypted communication between clients (e.g., browsers, apps) and servers over networks. TLS (successor to SSL, now TLS 1.3 in 2025) is the standard for securing HTTP (HTTPS), email (SMTPS), and more. Certificates bind a public key to an identity (server/domain) via a trusted authority, ensuring confidentiality, integrity, and authenticity.
What Are SSL/TLS Certificates?
- Definition: An X.509-structured file containing a public key, identity info (e.g., domain
example.com), and a digital signature from a Certificate Authority (CA) like Let's Encrypt, DigiCert, or Google Trust Services. Private key (secret) is kept separate. - Components:
- Public Key: For encryption/verification.
- Subject: Entity (e.g., CN=example.com).
- Issuer: CA that signed it.
- Validity: Expiry date (e.g., 90 days for Let's Encrypt).
- Extensions: SANs (Subject Alternative Names for multiple domains), key usage.
-
Types: | Type | Description | Use Case | |------|-------------|----------| | Domain Validated (DV) | Basic domain control (email challenge). | Quick sites (free from Let's Encrypt). | | Organization Validated (OV) | Verified company info. | Business sites. | | Extended Validation (EV) | Rigorous vetting (green bar in browsers, deprecated). | High-trust (banks). | | Wildcard | Covers subdomains (.example.com). | Multi-subdomain apps. | | Client Certs* | For mTLS (mutual auth). | API clients. |
-
Chain of Trust: Root CA (trusted by OS/browsers) → Intermediate CA → Server Cert. Browser verifies chain.
How TLS Certificates Secure Client-Server Interactions
TLS uses certificates in a handshake to establish an encrypted session, followed by secure data exchange.
TLS Handshake Process (TLS 1.3 Simplified)
- Client Hello: Client sends supported ciphers, random nonce, Server Name Indication (SNI: example.com).
- Server Hello: Server selects cipher, sends cert chain (server cert + intermediates), random nonce.
- Certificate Verification:
- Client validates cert chain against trusted roots (e.g., browser's CA store).
- Checks expiry, revocation (OCSP/CRL), hostname match (SNI/CN/SAN).
- Extracts server's public key.
- Key Exchange: Client generates ephemeral key pair (e.g., ECDHE); encrypts pre-master secret with server's public key (or uses Diffie-Hellman).
- Session Keys: Both derive symmetric keys (AES-GCM) from pre-master for encryption.
- Finished: Mutual verification (HMAC of handshake); session established.
- Application Data: Encrypted bidirectional communication (e.g., HTTPS POST).
Full Flow Diagram (Text-Based):
Client ── Client Hello (SNI, Ciphers) ──► Server
Server ── Server Hello + Cert Chain + Nonce ──► Client
Client ── Verify Cert (Chain, Expiry, Host) ── Internal
Client ── Key Exchange (Ephemeral DH) ──► Server
Both ── Derive Symmetric Keys (AES) ── Internal
Client/Server ── Encrypted Data Exchange ──◄► (Confidential, Integrity)
Security Properties Achieved
- Confidentiality: Symmetric encryption (AES) protects data in transit.
- Integrity: HMAC or AEAD (AES-GCM) detects tampering.
- Authentication: Server cert proves identity (client trusts CA-signed chain).
- Forward Secrecy: Ephemeral keys (e.g., ECDHE) ensure past sessions safe if private key compromised.
Certificate Lifecycle
- Generation: Create CSR (Certificate Signing Request) with private key; send to CA.
- Issuance: CA verifies (DV: email; OV/EV: docs), signs, returns cert.
- Installation: Server loads cert/private key (e.g., NGINX
ssl_certificate). - Renewal: Auto via ACME (Let's Encrypt); monitor expiry.
- Revocation: If compromised, publish CRL/OCSP; clients check on connect.
Nuances:
- Hostname Matching: Cert's CN/SAN must match SNI (e.g., *.example.com for subdomains).
- Chain Validation: Client walks to root CA (pre-installed in trust store).
- OCSP Stapling: Server includes revocation status in handshake (faster than client query).
- 2025 Trends: Let's Encrypt dominant (free, auto-renew); post-quantum certs emerging (e.g., ML-KEM).
Pros: Ubiquitous security; automatic in browsers. Cons: Cert management (expiry, revocation); CA trust issues.