Authentication (Session Vs JWT)
Explained as simply as possible… but not simpler.
Authentication vs Authorization
Authentication and Authorization solve two fundamental security questions in any system:
- Authentication : “Who are you?” - Proving and verifying user identity
- Authorization : “What are you allowed to do?” - Determining permissions and access rights
After a user logs in once, the system needs a way to “remember” them across multiple requests without asking for credentials repeatedly. There are two fundamentally different approaches to maintaining logged-in state
- session-based authentication
- JWT-based authentication
Session-Based Authentication
Key characteristic : The server stores session state, making it stateful. Session ID is just a reference key.
Components:
- Cookie : Contains session ID (small, opaque string)
- Session Store : Centralized storage (Redis, database, Memcached)
- Session Data : User ID, expiration, metadata stored server-side
JWT-Based Authentication
Key characteristic : No server-side storage, making it stateless. All data is in the token itself.
JWT Structure (three parts separated by dots):
header.payload.signature
Example:
eyJhbGc... . eyJ1c2Vy... . SflKxwRJ...
[algorithm] [user data] [signature]
Signing Algorithms:
- HMAC (HS256) : Symmetric - same key for sign & verify (simpler, faster)
- RSA/ECDSA : Asymmetric - private key signs, public key verifies (more secure for distributed systems)
Token Refresh Pattern (Best Practice for JWT)
Access Token (short-lived: 15 min) ────┐
├──▶ Regular API requests
Refresh Token (long-lived: 7 days) ────┘
│
└──▶ Only sent to /refresh endpoint when access token expires


