Articles/Phase 2 — HTTP & Data Wire Protocols

Authentication and Authorization for Backend Engineers

The evolution of identity, stateful sessions vs stateless JWTs, cookies, API keys, OAuth 2.0/OIDC delegation, RBAC, and timing attack mitigation.

Core Concept & First Principle

Authentication determines 'Who are you?' (identity verification), while Authorization determines 'What can you do?' (permissions). Modern backends balance centralized stateful sessions (Redis + cookies) for instant revocation against stateless JWTs for distributed horizontal scale, hardening systems with generic error responses, constant-time comparisons, and OAuth 2.0 delegation.

1. Authentication vs. Authorization: The 'Who' vs. The 'What'

Every secure backend system separates access control into two distinct, sequential phases: verifying identity first, and then validating permissions.

1Authentication (AuthN — The 'Who')

The mechanism that verifies the claimed identity of an incoming client or user. It answers: 'Who are you in this context?' (e.g., verifying a password hash or JWT signature).

2Authorization (AuthZ — The 'What')

The mechanism that evaluates a verified user's permissions against the requested resource. It answers: 'What actions are you allowed to perform?' (e.g., can this user delete a database record?).
The Status Code Rule (401 vs 403)
Return 401 Unauthorized when credentials are missing or invalid ('I do not know who you are'). Return 403 Forbidden when the identity is verified, but lacks sufficient permissions ('I know who you are, but you cannot access this').

2. The Historical Evolution of Identity & Hashing

Understanding how security evolved explains why modern backend protocols are designed the way they are:

Comparison Table↔ Scroll horizontally
EraMechanismVulnerability & Innovation
Pre-IndustrialImplicit Village TrustPersonal vouching and handshakes. Zero technical scalability beyond local communities.
MedievalWax Seals & Physical SignetsAuthentication based on possession. Gave rise to early physical forgery attacks.
IndustrialTelegraph PassphrasesShifted security to 'something you know' across long-distance wire communications.
1960s MainframesPlaintext Passwords ➔ HashingAn accidental password file print at MIT led to the invention of one-way cryptographic hashing (irreversible mathematical transforms like bcrypt/Argon2).
Modern MFAMulti-Factor AuthenticationCombines Knowledge (Password), Possession (Authenticator OTP / Phone), and Inherence (Biometrics).

3. Stateful Sessions vs. Stateless JWTs

Because HTTP is fundamentally stateless, backend engineers use two primary patterns to maintain user authentication across requests:

1Stateful Sessions (Server-Side Memory)

Upon login, the server creates a unique Session ID, stores the user context in an in-memory database (like Redis), and sends the ID to the client in an HttpOnly, Secure cookie. This allows instant server-side revocation, but requires centralized storage lookups.

2Stateless JWTs (Client-Side Tokens)

The server signs an encoded JSON token containing user claims (sub, exp, role) using a private secret key. The client attaches this token to every request header. Servers verify the cryptographic signature in memory with zero database lookups, making it ideal for distributed microservices.
Comparison Table↔ Scroll horizontally
FeatureStateful Sessions (Redis/DB)Stateless JWTs
Storage LocationServer-side store (Redis / Database)Client-side (Memory / HttpOnly Cookie)
RevocationInstant (delete session from Redis)Difficult before token expiration (requires token blocklists)
Microservice ScalingRequires shared cache lookup on every hopZero database hits; verified locally via shared secret
Payload SizeTiny (32-character opaque Session ID)Larger (base64 encoded JSON string with claims)

4. JWT Anatomy & Secure Cookie Transport

A JSON Web Token consists of three base64url-encoded components separated by dots (.):

Example: JWT Anatomy Breakdown
INPUT / REQUEST
// 1. HEADER (Algorithm & Type)
{ "alg": "HS256", "typ": "JWT" }

// 2. PAYLOAD (Claims)
{ "sub": "usr_8f9a2b1c", "role": "admin", "exp": 1786973600 }

// 3. SIGNATURE (HMAC-SHA256)
HMACSHA256(base64Url(header) + "." + base64Url(payload), secretKey)
OUTPUT / RESULT
// 4. COMPLETE WIRE TOKEN TRANSMITTED OVER HTTP
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfOGY5YTJiMWMiLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3ODY5NzM2MDB9.i_7E9WbM-4Y0U_8h1O1k7qN9QWq2e5R
Takeaway:If an attacker tampers with any character in the payload (like changing role to admin), the signature fails verification immediately.
The Golden Cookie Rule
Always transmit session tokens inside cookies configured with: HttpOnly (blocks malicious JavaScript from stealing tokens during XSS attacks), Secure (enforces HTTPS-only transmission), and SameSite=Strict (prevents CSRF attacks).

5. API Keys, OAuth 2.0 & OpenID Connect (OIDC)

1API Keys (Machine-to-Machine)

High-entropy random strings used by automated servers and SDKs to bypass human login interfaces and authenticate background microservice jobs.

2OAuth 2.0 (Delegated Authorization)

Solves the 'Delegation Problem' where users previously had to share master passwords with third-party apps. OAuth grants scoped, revocable access tokens (e.g. 'read-only contacts access') without sharing passwords.

3OpenID Connect (OIDC Identity Layer)

An identity protocol built on top of OAuth 2.0. It introduces standardized ID Tokens (JWTs) containing profile data (email, name), powering modern 'Sign in with Google' federated authentication.

6. Role-Based Access Control (RBAC)

RBAC restricts system access based on assigned user roles. Backend middleware intercepts requests, extracts user claims, and checks if the role possesses the required permission before running business logic.

1function requireRole(allowedRoles) {
2 return (req, res, next) => {
3 if (!req.user || !allowedRoles.includes(req.user.role)) {
4 return res.status(403).json({ error: '403 Forbidden: Insufficient permissions' });
5 }
6 next();
7 };
8}
9
10app.delete('/api/database', requireRole(['admin']), (req, res) => {
11 res.json({ message: 'Database operation executed' });
12});

7. Critical Security: Generic Errors & Timing Attack Mitigation

Building secure authentication requires protecting against subtle side-channel attacks:

1Generic Error Messages (Prevent Enumeration)

Never return specific messages like 'User not found' or 'Incorrect password'. Attackers use these to harvest lists of registered emails. Always return a uniform 'Invalid email or password'.

2Equalized Latency & Constant-Time Comparisons (Prevent Timing Attacks)

Password hashing (Argon2 / bcrypt) takes ~100ms. If an invalid username returns in 1ms while a valid username returns in 100ms, attackers measure response time to identify valid users. Perform dummy hashes or constant-time comparison to ensure uniform latency.
Example: Constant-Time Login Implementation
INPUT / REQUEST
POST /api/auth/login HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "email": "nonexistent_user@example.com",
  "password": "wrong_password_123"
}
OUTPUT / RESULT
HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
  "error": "Invalid email or password"
}
Takeaway:Even though the user does not exist, the server executes a dummy hash step, returning 401 in constant ~120ms to completely neutralize timing analysis.
Summary & Core Takeaways
Key Insights
1Authentication verifies identity ('Who are you?'); Authorization evaluates permissions ('What can you do?').
2401 Unauthorized means credentials are missing or invalid; 403 Forbidden means the identity is valid but lacks required privileges.
3Stateful sessions (Redis + HttpOnly cookies) provide instant revocation; Stateless JWTs offer horizontal scalability across microservices without database lookups.
4Always use generic error messages ('Invalid email or password') and constant-time comparisons to prevent account enumeration and timing attacks.
5OAuth 2.0 delegates scoped permissions to third parties without sharing master passwords; OpenID Connect (OIDC) standardizes federated user identity.
API Sandbox (3 Live Endpoints)
Authentication
Live API

19. Login & Token Issuer (JWT vs Session)

Simulates secure credential verification with constant-time timing protection, generic error responses, and dual issuance of stateless JWT and stateful Session ID.

Headers:Content-Type: application/json
Request Body (JSON Payload)Valid JSON
Authentication
Live API

20. Stateless JWT Signature Verification

Cryptographically verifies the HMAC-SHA256 signature and decodes token claims in memory without requiring any database lookups.

Headers:Content-Type: application/json
Request Body (JSON Payload)Valid JSON
Authorization
Live API

21. Role-Based Access Control (RBAC Guard)

Enforces permission boundaries across viewer, editor, and admin roles, differentiating 401 Unauthorized from 403 Forbidden.

Headers:Content-Type: application/json
Request Body (JSON Payload)Valid JSON