Hello! Grab a coffee or tea first, sit down and relax. The topic of authentication and authorization is indeed everyday food in the world of software engineering, but the funny thing is that it often creates a heated debate in the architectural space. Starting from engineers who insist on using JSON Web Tokens (JWT) for internal dashboards are simple until you end up having a headache thinking about the mechanism for token revocation, until the team is forced to use database-based sessions in a distributed microservices architecture until the database is gasping for validation queries every millisecond.
As an engineer who has repeatedly experienced the system crashing at 2 am because of choosing the wrong auth foundation, I will thoroughly analyze these three things: Sessions, JWT, and OAuth. We will thoroughly examine the basic concept in human terms, dissect the advantages and disadvantages through real case studies in the industrial world, and create clear architectural guidelines for when you should use each of these mechanisms.
1. Dissecting Basic Concepts: What Actually Are They?
Before getting into the technicalities of offal, we have to equalize our perceptions first. HTTP is basically a stateless protocol. This means that the server is a heavy forgetter. Once request A has finished responding, then the browser sends request B one second later, the server by default has no memory whatsoever that request B came from the same person as request A.
Auth mechanisms exist to provide a "memory" or identity label to these stateless interactions.
A. Statefull Session (Session-Based Auth)
Imagine you check into a five-star hotel. You come to the receptionist, show your KTP and proof of booking. The receptionist checks the computer, then gives you a physical key (room number 302). In the hotel's computer system, it is recorded: Physical key #302 is currently held by Sigit, valid until tomorrow at 12 noon.
Every time you want to enter the elevator or open a room door, you just tap the key. The key itself does not contain your personal data; the key is just a piece of plastic with a unique string (token/session ID). The hotel computer is tasked with matching the key ID to the guest data in their database.
Here's Session-based authentication:
-
User sends email and password to the server.
-
The server validates the credentials to the database.
-
If they match, the server creates a new session record (in memory, Redis, or database) containing
Session ID,User ID, login status, and expiration. -
The server sends
Session IDback to the browser via theSet-Cookieheader (usually set with theHttpOnly,Secure, andSameSite). -
On each subsequent request, the browser automatically includes this cookie.
-
The server takes the session ID from the cookie, matches it to session storage (stateful), then processes the request if it is valid.
B. Stateless Token: JSON Web Token (JWT)
Now imagine a different scenario. You come to an international music festival that has dozens of independent stages without a stable centralized internet connection. When you buy a ticket at the front door, the committee prints a special laminated paper bracelet that says: "Name: Budi, Access: VIP, Valid until: 23.00 WIB". The bracelet is stamped with the committee's official embossed stamp which is impossible to fake without the special stamp of the head of the festival.
Every time you want to enter Stage A, B, or C, the doorman doesn't need to call the head office or open a database. They just need to look at your bracelet, touch the official stamp (validating the cryptographic signature), and read the access rights written on it. If the stamp is valid and the time has not passed, please come in.
Here's JWT:
-
User logs in with regular credentials.
-
The server validates the user, then creates a long, base64url-encoded string consisting of three dot-separated parts (
Header.Payload.Signature).
-
Header: Hashing algorithm used (e.g. HS256, RS256).
-
Payload (Claims): User data (eg:
sub: 123,role: "admin",exp: 1718000000). -
Signature: Cryptographic hash of the Header + Payload combination using a secret key / private key known only to the server.
-
-
This token is sent to the client. The server does not store anything in its memory (stateless).
-
In each subsequent request, the client sends this token (usually in the header
Authorization: Bearer). -
The server simply verifies the signature mathematically using a public key or secret key. If the signature matches and has not expired, the server immediately trusts the contents of the data without needing to query the database.
C. Authorization Delegation Protocol: OAuth 2.0
This is the biggest misconception that often occurs among junior engineers: thinking that OAuth is a direct alternative to Session or JWT.
Fundamental notes: Session and JWT are ways store/represent authentication state, while OAuth 2.0 is an authorization delegation protocol.
Back to the real world analogy: You live in a modern apartment. You order a cleaning service via the application. You don't want to give the master key to your apartment (username & password) to the cleaner, because if you give him the master key, he can open the safe, open the wardrobe, and come whenever he pleases.
Instead of giving you a master key, you ask the apartment building manager to issue a temporary guest access card (valet key) which can only be used to open the front door of your apartment from 14.00 to 16.00, without access rights to the safe or main room.
OAuth 2.0 works exactly like that. OAuth allows a third-party application (Third-Party App) to access a user's resources on another server (Resource Server) without ever knowing the user's password. For example, you let Canva access photos in your Google Drive without having to type your Google password in the Canva application.
If you add an OpenID Connect (OIDC) layer on top of OAuth 2.0, then this protocol can be used for the authentication process (Login with Google, Sign in with Apple, GitHub, etc).
2. Surgical Advantages & Disadvantages Based on Real Case Studies
The theory is beautiful until your application is released to production and it starts getting hit by thousands of requests at once. Let's evaluate each approach using real case studies.
Case 1: Monolithic Web Application (ERP, Backoffice, Campus Portal/MSME SaaS)
Characteristics: Server-Side Rendering (SSR) or Monolith (Laravel, Django, Rails, Spring Boot), user access via desktop/mobile browser, tight control over user sessions.
Preferred Approach: Stateful Session
Browser Monolith Server Redis / DB
| | |
|-- 1. POST /login (user/pass) ---->| |
| |-- 2. Validate user --------->|
| |-- 3. Create Session (123) -->|
| |<-- Session Stored -----------|
|<- 4. Set-Cookie: sid=123 (HttpOnly)| |
| | |
|-- 5. GET /dashboard (Cookie: 123)->| || |-- 6. Check Session (123) --->|
| |<-- Valid, User ID: 45 -------|
|<-- 7. 200 OK (HTML/Data) ---------| |
Advantages:
-
Instant Revocation (Perfect Kill Switch): This is the number one advantage of sessions. Imagine that the HR admin fires a naughty employee at 10.15. As soon as the admin clicks "Revoke Access" or "Force Logout", the server immediately deletes the employee's session key in Redis. At 10.16 seconds, when the employee tried to click the "Download Salary" button, his request was immediately rejected (401 Unauthorized). There is no tolerance gap.
-
Built-in Security Against XSS: Session cookies configured with the
HttpOnlyflag are impossible to read by malicious JavaScript scripts injected via Cross-Site Scripting (XSS). Your token is safe in the deepest drawer of the browser. -
Light Payload on the Network: Session cookies are usually just short random strings (32–64 characters). Compare this with JWT which can be 1–2 KB in size because it is packed with various data claims. Sending 32 bytes is much more bandwidth efficient than 2 KB per request when traffic hits millions.
-
Data is Always Fresh: Because the server is always reading the session store or validating to the DB/cache, user role changes (eg: being demoted from Manager to Staff) take effect immediately on the next request.
Disadvantages:
-
Bottleneck State Storage: The server must maintain state. If your application has 100,000 users logging in simultaneously, that means there are 100,000 entries in memory/Redis.If Redis goes down or saturates, the entire application authentication flow immediately crashes.
-
Horizontal Scaling Challenges: If you have multiple servers behind a Load Balancer, you can no longer rely on the physical server's built-in in-memory sessions (because the first request can fall to Server A, the second request to Server B). You are required to setup a central session store (such as Redis Cluster) or sticky sessions (which is less ideal).
-
CSRF Vulnerability: Because browsers automatically include cookies in every cross-domain request, cookie-based applications are vulnerable to Cross-Site Request Forgery (CSRF). You must implement CSRF Token protection (
SameSite=Lax/Strict, anti-forgery tokens in POST/PUT forms). -
Less Native Mobile App Friendly: Mobile apps (Android/iOS) do not have automatic cookie handling mechanisms as clean as web browsers. Managing cookie jars in mobile apps requires extra configuration than simply embedding the token in the HTTP header.
Case 2: Distributed Microservices & Single Page Application (SPA / Mobile)
Characteristics: Separate frontend (React, Vue, Flutter, iOS Swift), backend consists of dozens of independent microservices (User Service, Order Service, Payment Service, Notification Service), high traffic.
Preferred Approach: JSON Web Token (JWT)
Client (SPA/Mobile) API Gateway / Auth Service Order Microservice
| | |
|-- 1. POST /login ----------------->| |
|<- 2. Return JWT (Signed) ----------| |
| |
|-- 3. GET /orders (Header: Bearer ) ------------------------------->|
| | (Microservice verifies || | signature via Public Key |
| | without calling Auth Service!) |
|<-- 4. 200 OK (Order Data) -----------------------------------------------|
Advantages:
-
Stateless & Full Decentralization: This is JWT's superpower. The Order Service above does not need to open a connection to the Auth database or fire the User Service API to ensure whether the person calling the request is a valid user. Order Service simply validates the JWT signature using the Public Key (RS256 asymmetric algorithm). This breaks network latency and eliminates single points of failure at the authentication level.
-
Highly Scalable: Add 50 new server instances in kubernetes cluster? No problem. The new server does not need any session storage synchronization. Just provide the environment variable public key to validate the token.
-
Cross-Domain & Mobile Friendly: JWT is stored in client memory or Secure Storage (Keystore/Keychain on Android/iOS) and sent via header
Authorization: Bearer. This mechanism is naturally immune to CSRF attacks because the browser does not automatically send it like cookies. -
Self-Contained Data: You can embed essential metadata in the token payload, such as
tenant_id,role, anduser_id. The destination microservice can directly extract this data for authorization without needing to query the basic profile data repeatedly.
Disadvantages:
-
The Invalidation Nightmare (Token Cannot be Revoked): This is the biggest sin of pure JWT architecture. Once a JWT is signed and sent to the client, the token is valid until its expiration date expires. If a user's account is hijacked, or the user's laptop is stolen, or the user's role is revoked by the admin at this moment, the user can still access the API as long as the token has not expired.
-
Compromise solution: Many teams end up creating a “Blacklist Token” in Redis. But wait: if you check Redis on every request to see if the token is blacklisted, congratulations! You've just changed your stateless system back to a stateful session with a more complicated and bandwidth-intensive format.
-
-
Swelling Data Size: JWT payloads containing user information, permission lists, issuers, and timestamps easily reach sizes of 1 KB to 3 KB. If a SPA application makes 30 concurrent API requests on one page, you are transferring tens of kilobytes the same auth metadata over and over again over the wire protocol.
-
Storage Security Risks on Client: If JWT is stored in
localStorageorsessionStoragebrowser, these tokens are vulnerable to being stolen via XSS attacks. Once a malicious third-party script (e.g. from a compromised npm dependency) manages to run, they can readlocalStorage.getItem('token')and send it to the attacker's server. -
Stale Data (Expired Data): If you save
role: "editor"in the JWT payload, then a minute later the user is promoted to "admin", the system will not know about the change until The old token expires and the user gets a new token.
Case 3: Multi-App Ecosystems & Third Party Integrations (API Platforms / Social Login)
Characteristics: Your app wants to provide a "Login with Google/Apple" feature, or your app wants to open a Public API to allow third parties to build plugins (like the Shopify ecosystem, Slack, or GitHub Apps).
Preferred Approach: OAuth 2.0 / OpenID Connect (OIDC)
User Client App (Canva) Authorization Server (Google) Resource Server (Drive)
| | | |
|-- 1. Click "Import Drive"->| | |
|<-- 2. Redirect to Google-| | |
|-- 3. User gives permission ---->| | |
|<-- 4. Redirect to Canva with Authorization Code --------| |
| | | |
| |-- 5. Exchange Auth Code + Secret ->| |
| |<- 6. Return Access Token & Refresh Token |
| | |
| |-- 7. GET /photos (Header: Bearer Access Token) -------------->|
| |<-- 8. Image Files Allowed ----------------------------------|
Advantages:
-
Security Without Sharing Credentials: Users never hand over their original passwords to third-party applications. Trust remains in the hands of a trusted Identity Provider (IdP) such as Google, Microsoft, or your internal auth server.
-
Granular Scopes (Specific Access Rights): Users can provide precise access rights. For example: only
read:profileandread:emailpermissions, nowrite:profileor access to financial data. -
Identity Centralization (Single Sign-On / SSO): For enterprise level with dozens of internal applications (Jira, Slack, HR Portal, Gitlab), employees only need to have one account at an Identity Provider (Okta, Keycloak, Azure AD) and log in to all systems via OAuth/OIDC flow.
-
Standardized Revocation: Users can log in to the Google Security dashboard and revoke "Canva" access at any time. When access is revoked, the tokens held by Canva are immediately useless.
Disadvantages:
-
High Implementation Complexity: Building your own OAuth 2.0 Authorization Server from scratch is not an easy job. There are various flow/grant types (Authorization Code with PKCE, Client Credentials, Refresh Token grant) which are vulnerable to fatal security holes if misconfigured (eg: redirect URI manipulation, token leakage, CSRF in the auth flow).
-
Network Overhead: The round-trip authentication flow (redirect, exchange of authorization code for token, validation of token via introspection endpoint) requires more network round-trip latency than simple login.
-
External Dependencies: If you rely purely on Google/GitHub OAuth for user authentication and their service is down or the local network is blocking access to their domain, your users won't be able to log in to your app at all.
3. Comprehensive Comparison Between Approaches
The following table summarizes the fundamental trade-offs between these three pillars:
| Evaluation Parameters | Stateful Session | JSON Web Token (JWT) | OAuth 2.0 / OIDC |
| Main Category | Login status mechanism | Structured token format | Authorization & delegation protocols |
| State Storage | On the server (Redis/DB/Memory) | Stateless (on client) | Centralized on Authorization Server |
| Session Invalidation | Instant, easy, deterministic | Very difficult without a centralized blacklist | Token revocation mechanism available |
| Client Store | HTTP Cookie (HttpOnly) |
LocalStorage, Memory, or Secure Cookie | Secure storage on client/backend client |
| Size Overhead | Very small (~32-64 bytes) | Medium to Large (500B - 3KB) | Variable (opaque token or JWT) |
| Vertical Scalability | Limited to store capacity | Very high (local verification) | High (with separate IdP architecture) |
| Major Risks | CSRF, Session Store Bottleneck | XSS, Token Leakage, Expired Data | Incorrect flow configuration, redirect gap |
| Best Case | Monolith, Admin Dashboard, Web SSR | Microservices, Native Mobile App API | Social Login, Enterprise SSO, Public API |
4. Architectural Recommendations: When to Use Which?
As a senior engineer, I will not give cliche answers like "depends on your needs", but rather a concrete rule of thumb (rule of thumb) that you can use as a checklist architectural decisions.
[ Start Auth Designing ]
|
Does it involve third parties/
Multi-app SSO / Social Login?
/\
Yes No
/\
[ Use OAUTH 2.0 ] Is the architecture Monolith
(OIDC: Google/Keycloak) or Server-Side Rendered (SSR)?
/\
Yes No (SPA / Mobile)
/\
[ Use SESSIONS ] Does it need renovation
(Redis + HttpOnly) instant / strict session control?
/\
Yes No (Decentralization)
/\
[ SESSION / SHORT-LIVED JWT ] [ PURE JWT (RS256) ]
(Hybrid Pattern via Gateway) (Stateless Verification)
Scenario A: Use SESSIONS if...
-
Your application is a Monolith (Laravel, Django, Ruby on Rails, Next.js Fullstack).
-
Don't act cool by separating the Laravel backend just to make it a pure API and then the React frontend separately if your team only has 2-3 people. Use the framework's built-in sessions. Save sessions in Redis.
-
Set a cookie with the required flag:
HttpOnly = true,Secure = true,SameSite = LaxorStrict. You are instantly safe from 99% of token theft XSS attacks.
-
-
You build banking, financial, internal admin or B2B SaaS applications.
-
In this domain, the ability to kick a user out at a moment's notice is a prerequisite for security audit compliance (compliance). If there are indications of fraud, the CS or antifraud system must be able to immediately shut down the user session. Session is the absolute winner here.
-
-
Your team is small and needs speed of delivery without complicated overhead.
-
Managing refresh token rotation, payload sanitization, and public-private key pairs in JWT is time consuming and prone to security holes if the team's understanding of cryptography is not yet mature. Session has been around for 30 years in the web industry.
-
Scenario B: Use JWT if...
-
Your architecture is massive scale Microservices.
-
Where one request from the user will be forwarded to 10-15 sub-services on the backend.
-
Here, local validation via Public Key (RS256 or Ed25519) saves thousands of network calls between services. Your auth database won't crash just because of "who requested this?"
-
-
Your application primarily serves the Native Mobile Client (iOS / Android).
-
The mobile ecosystem works more naturally with the header
Authorization: Bearer. Tokens can be stored securely in the Android Keystore or iOS Keychain (which is much more resilient to malware than the browser'slocalStorage).
-
-
Hybrid Design Patterns (Industry Best Practice for SPA & Modern Web):
-
If you have to use JWT for SPA (Single Page Application), don't use pure stateless. Use the pattern Short-Lived Access Token + Long-Lived Refresh Token:
-
Access Token: Contains a JWT with a super short lifetime (5 to 15 minutes). Store only in JavaScript memory (internal variables), do not store in
localStorage. -
Refresh Token: Random string (not a JWT, or a hashed JWT in DB/Redis) with a long lifetime (7 to 30 days). Send it back to the browser via HttpOnly Secure Cookie.
-
The flow: Every 15 minutes, the application transparently requests a new Access Token to the
/refreshendpoint using the Refresh Token cookie. If the user is blocked by the admin, the server simply deletes the Refresh Token record in the database. In a maximum of 15 minutes, the user's access will be permanently disabled because they cannot renew the Access Token.
-
-
Scenario C: Use OAUTH 2.0 (and OIDC) if...
-
You want to provide the "Register / Login with Google, Apple, Facebook, or GitHub Account" option.
-
Never create a complicated registration form if your target market is casual users. Use OIDC. Let Google verify their OTP, 2FA, and password reset. You simply receive a verified Token ID and retrieve their email address.
-
-
Your application is an Open Platform that invites outside developers.
-
You are building an application such as accounting or e-commerce SaaS, and want other developers to be able to create integrations (for example: delivery courier integration or Telegram bots).
-
Here OAuth 2.0 with Authorization Code Grant with PKCE is the industry standard.
-
-
Internal Enterprise Ecosystem (Centralized SSO).
-
Your company has dozens of separate tools. Instead of creating a
userstable in each application database, build one centralized Authorization Server (for example using open-source like Keycloak, Authentik, or SaaS like Auth0/Clerk). Other applications simply act as an OAuth Client.
-
5. Senior Engineer Principles Summary
Being a senior engineer is not about how sophisticated the technology you bring to the table is, but rather how appropriate the solution you choose is given the problem context, team size, and threat model (threat model) of your application.
-
Don't kill mosquitoes with cannons: If your application is an office inventory information system or local cashier application, use Redis-based Sessions. Your system is stable, user engagement is instant, code is clean, and you can sleep soundly on the weekends.
-
-
Use OAuth to limit delegation of access rights: Treat OAuth as a bridge for delegation of authority between independent systems or for enterprise SSO, not just a replacement for a regular login session form.
Choose tools that solve your business problems today without creating security holes and technical debt that you'll have to pay for by staying up late in the future.

Sigit Wasis Subekti
Software Engineer & Tech Educator
Software Engineer and Tech Educator sharing insights on web development and software architecture.