Stateful Sessions, Stateless JWT Verification, Access vs Refresh Lifecycles, & OAuth 2 Delegation Flow
1 Stateful Session-Based Authentication
In traditional web applications, authentication is Stateful. The server creates and retains an active session record in a centralized fast data store (e.g., Redis) for every logged-in client:
1 Initial Credentials Submission
Browser β ServerPOST /login { username, password }) over HTTPS.2 Create Session Record
Server β RedisSession ID, and writes user context to Redis (TTL 24h).3 Session Persistence Confirmed
Redis β Serversession_id: sess_98432a1.4 Set Secure Cookie Header
Server β BrowserSet-Cookie: sid=sess_98432a1; HttpOnly; Secure; SameSite=Strict.β‘ Subsequent Protected Requests Loop β‘
5 Automatic Cookie Attachment
Browser β ServerGET /api/dashboard; HTTP client attaches cookie Cookie: sid=sess_98432a1 automatically.6 Session Lookup Query
Server β RedisGET session:sess_98432a1 to fetch user roles, permissions, and status.7 Return Session State
Redis β Server{ userId: 42, role: βadminβ, exp: β¦ }).8 Authorized Payload Delivery
Server β Browser200 OK.2 Stateless Token-Based Authentication (JWT Bearer Flow)
To scale across horizontally distributed microservices without querying a centralized session store on every HTTP call, modern systems use Stateless JWT Bearer Tokens:
π§© The 3 Parts of a JSON Web Token (JWT)
{ βalgβ: βRS256β, βtypβ: βJWTβ }
{ βsubβ: β42β, βroleβ: βadminβ, βexpβ: 171400 }
HMACSHA256(b64(H) + β.β + b64(P), secret)
1 Authentication Request
Client β Auth ServerPOST /auth/login).2 Validate & Sign Token
Auth Server Internal3 Issue Signed JWT
Auth Server β Clientβ‘ Zero-Lookup API Consumption β‘
4 Bearer Token Request
Client β API MicroserviceAuthorization: Bearer <signed_jwt_token>.5 Local Signature Verification (No DB Hit!)
API Microservice Internal6 Direct Resource Response
API Microservice β Client200 OK).Massive Horizontal Scalability: Any API microservice across multiple data centers can independently authenticate requests using only a cached public key.
Revocation Difficulty: Because verification is completely stateless, invalidating a leaked token before its expiration requires maintaining a distributed blacklist or using very short TTLs.
3 Access & Refresh Token Dual-Lifecycle
To balance security (limiting leak damage) and user experience (avoiding frequent re-logins), modern architectures adopt a Dual-Token Strategy:
β‘ Access Token
Short-lived; sent with every API request via Authorization: Bearer header. If intercepted, attacker window is strictly minimized.
π Refresh Token
Long-lived; stored exclusively in secure HttpOnly cookies; used only at /auth/refresh to mint fresh access tokens.
1 Initial Dual-Token Issuance
Auth Server β ClientHttpOnly cookie (30d).2 Expired Access Token Rejection
Resource Server β Client401 Unauthorized (jwt expired).3 Silent Background Refresh Request
Client β Auth ServerPOST /auth/refresh (sending HttpOnly refresh cookie).4 Token Rotation & New Access Token
Auth Server β Client5 Transparent Request Replay
Client β Resource ServerNever store Refresh Tokens in localStorage or sessionStorage!
Any Cross-Site Scripting (XSS) vulnerability allows attackers to exfiltrate local storage items. Always store Refresh Tokens inside HttpOnly, Secure, SameSite=Strict cookies so client-side JavaScript cannot access them.
4 OAuth 2.0 Authorization Code Flow (Delegation)
OAuth 2.0 is an Authorization Delegation Framework enabling a third-party application to access user resources from an API without ever exposing user credentials:
1 User Initiates Third-Party Connection
User β Your App2 Browser Redirect to Consent Dialog
Your App β Google OAuth3 Consent Confirmation
User β Google OAuth4 Authorization Code Returned via Redirect
Google OAuth β Your Apphttps://yourapp.com/callback?code=spl_auth_code_91823.5 Backend Code Exchange (Direct Server-to-Server)
Your Backend β Google OAuthcode=spl_auth_code_91823 + client_secret to Google token endpoint.6 Access Token Issued
Google OAuth β Your Backenddrive.readonly.7 Scoped API Data Request
Your App β Google Drive APIAuthorization: Bearer <access_token>.8 Protected Files Returned Securely
Google Drive API β Your App5 OpenID Connect (OIDC): Adding Identity & Authentication
OpenID Connect (OIDC) is an identity layer built directly on top of OAuth 2.0 that allows clients to verify user identity and obtain verified profile information via a digitally signed ID Token (JWT format):
Focus: Authorization / Delegation
Answers: βWhat access does this app have?β Returns an Access Token intended for Resource Servers (APIs).
Focus: Authentication / Identity
Answers: βWho is the user?β Returns an ID Token (JWT) intended for the Client to read user identity claims.
1 User Clicks βSign in with Googleβ
User β Client App2 Redirect with openid Scope
Client App β Google IdPscope=openid profile email.3 User Authenticates & Approves
User β Google IdP4 Authorization Code Returned
Google IdP β Client App5 Code Exchange for Dual Tokens
App Backend β Google IdPPOST https://oauth2.googleapis.com/token).6 IdP Returns ID Token + Access Token
Google IdP β App Backendid_token (signed JWT with email, name, avatar) + access_token.7 Verify Signature & Link User Account
App Backend Internal8 Authenticated Session Established
App Backend β Client App6 Single Sign-On (SSO) & Federated Identity Architecture
Single Login Entry
Okta β’ Microsoft Entra ID (Azure AD) β’ Google Workspace β’ Keycloak
β¬οΈ Cryptographically Federated Trust (Zero Password Sharing) β¬οΈ
π‘ Centralized Security Control: When an employee departs, deactivating their account at the central IdP instantly terminates access across all 200+ connected enterprise applications without individual app de-provisioning.
7 Architectural Comparison: Sessions vs. JWTs vs. OAuth 2 / OIDC
Comprehensive decision matrix to select the right authentication and authorization paradigm for your system:
| Dimension | Stateful Sessions | Stateless JWT Tokens | OAuth 2.0 / OIDC |
|---|---|---|---|
| Primary Goal | User Authentication (AuthN) | User Authentication (AuthN) | Delegated Authorization + Identity |
| State Storage | Server-side (Redis, Database cluster) | Client-side (Signed cryptographic token payload) | Decentralized tokens with IdP key verification |
| Verification Cost | Database / cache network round-trip on every call | 0 DB Lookups: Pure local CPU signature verification | Public key (JWKS) cached verification or token introspection |
| Revocation Speed | Instant: Delete session key from Redis | Hard: Requires token blacklists or short expiry TTLs | Revoke token at IdP / token introspection endpoint |
| Payload Size | Tiny cookie (32-byte session ID) | Medium-large (500B β 2KB HTTP header overhead) | Medium-large (Access token + ID token JWTs) |
| Cross-Domain / Microservices | Hard (Requires sticky sessions / shared Redis) | Native: Passes seamlessly across microservices | Native: Federated across independent organizations |
| Best Suited For | Monolithic SSR web apps, banking & finance portals | High-scale microservices, mobile apps, SPA dashboards | Third-party integrations, enterprise SSO, Google sign-in |