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

Stateless Authentication

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

Advantages

Disadvantages

Standards & Flows

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

  1. Primary Auth: Username/password.
  2. Secondary Challenge: IdP sends factor (e.g., TOTP code via app).
  3. Verification: User submits; IdP validates (e.g., HMAC-based OTP).
  4. Success: Issue token/session.

Types of MFA

Advantages

Disadvantages

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)

  1. 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.
  2. Authentication: RP sends challenge; authenticator signs with private key; RP verifies signature with public key.
  3. Success: RP issues session/token.

FIDO2 Components

Advantages

Disadvantages

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"}

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

JWTs (JSON Web Tokens)

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

Refresh Token

Long-lived token used to obtain new access tokens without re-authentication.

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

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

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

mTLS (Mutual TLS)

DPoP (Demonstrating Proof-of-Possession)

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)

Introspection (RFC 7662)

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

In-Memory Storage

Secure Storage (Mobile/Native)

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)

2. Implicit Flow (Deprecated in OAuth 2.1)

3. Hybrid Flow

4. Client Credentials Flow

5. Device Authorization Flow

Nuance: Authorization Code + PKCE is the secure default for all clients.

Security Considerations

Implementation Overview

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

Short Expiry

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

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)

  1. Input: Password + salt (random 16-32 bytes).
  2. Derive Key: Run Argon2 with params (memory=64MiB, iterations=3, parallelism=4).
  3. Output: 32-byte hash (e.g., $argon2id$v=19$m=65536,t=3,p=4$...).
  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

Best Practices

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"]}'

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

Back-Channel Logout

Session Management in OIDC

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?

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)

  1. Client Hello: Client sends supported ciphers, random nonce, Server Name Indication (SNI: example.com).
  2. Server Hello: Server selects cipher, sends cert chain (server cert + intermediates), random nonce.
  3. Certificate Verification:
  4. Client validates cert chain against trusted roots (e.g., browser's CA store).
  5. Checks expiry, revocation (OCSP/CRL), hostname match (SNI/CN/SAN).
  6. Extracts server's public key.
  7. Key Exchange: Client generates ephemeral key pair (e.g., ECDHE); encrypts pre-master secret with server's public key (or uses Diffie-Hellman).
  8. Session Keys: Both derive symmetric keys (AES-GCM) from pre-master for encryption.
  9. Finished: Mutual verification (HMAC of handshake); session established.
  10. 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

Certificate Lifecycle

  1. Generation: Create CSR (Certificate Signing Request) with private key; send to CA.
  2. Issuance: CA verifies (DV: email; OV/EV: docs), signs, returns cert.
  3. Installation: Server loads cert/private key (e.g., NGINX ssl_certificate).
  4. Renewal: Auto via ACME (Let's Encrypt); monitor expiry.
  5. 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.