Token-Based Authentication (JWT)
About
Token-Based Authentication is a stateless authentication mechanism where a user is authenticated once and receives a token (typically JWT – JSON Web Token). This token is then sent in subsequent requests, eliminating the need for sessions.
JWT authentication is widely used in REST APIs, microservices, and Single Page Applications (SPAs) due to its scalability and security benefits.
How Token-Based Authentication Works (JWT Authentication Flow)
User Logs In
The user provides credentials (username/password) via a login API.
Server Validates Credentials
If credentials are valid, the server generates a JWT token and returns it.
Client Stores Token
The client (browser or mobile app) stores the token (e.g., LocalStorage, SessionStorage, HTTP cookies).
Client Sends Token in Requests
For every subsequent API request, the token is sent in the
Authorization
header.
Server Validates Token
The server verifies the token using a secret key or public-private key pair.
Access Granted or Denied
If the token is valid, the request is processed. Otherwise, an authentication error is returned.
JWT Structure
A JWT token consists of three parts:
Example:
1. Header
Contains metadata about the token, including the algorithm used for signing:
2. Payload (Claims)
Contains user information (claims):
sub
→ Subject (username)exp
→ Expiration timeroles
→ User roles
3. Signature
Used to verify token integrity:
JWT Authentication in Spring Boot
1. Dependencies
Add the following dependencies in pom.xml
:
2. Generate JWT Token
A service to generate JWT tokens:
3. Custom JWT Authentication Filter
Intercepts requests, extracts the token, and sets authentication context:
4. Configure Spring Security
Spring Boot 2 (Spring Security 5)
Spring Boot 3 (Spring Security 6)
JWT vs. Session-Based Authentication
Feature
JWT Authentication
Session-Based Authentication
State
Stateless
Stateful (session storage)
Scalability
High (suitable for microservices)
Low (server maintains session)
Security
Requires strong encryption
Sessions can be hijacked
Storage
Stored on the client (LocalStorage, HTTP Cookies)
Stored on the server
Revocation
Hard to revoke
Easy to revoke by destroying the session
Why is JWT Called Stateless?
JWT (JSON Web Token) is considered stateless because the server does not store any session-related information after issuing the token. Instead, all necessary authentication details (user identity, expiration time, roles, etc.) are embedded within the token itself and sent with each request.
Even though a JWT remains valid for a certain period (until expiration), the server does not maintain any record of issued tokens. Instead, validity is checked dynamically based on the token’s signature and expiration claim (exp
).
How JWT Differs from Stateful Authentication
Where is session data stored?
Inside the token (client-side)
On the server (session storage)
Does the server track sessions?
No, no need to track user sessions
Yes, maintains session storage
Scalability
High (since no session storage is needed)
Low (server must store & sync session data)
Token Revocation
Harder (token remains valid until expiration)
Easy (destroy session on logout)
When to Use Token-Based Authentication (JWT)?
JWT authentication is not always the best choice. It works well in certain scenarios but has limitations.
Use JWT When -
1. Building RESTful APIs & Microservices
JWT allows authentication to work across multiple independent services without requiring shared session storage.
Example: A microservices-based system where multiple services (e.g.,
UserService
,OrderService
,PaymentService
) need authentication without a central session store.
2. Stateless, Scalable Applications
If your app runs across multiple instances (e.g., Kubernetes, cloud environments), JWT helps avoid session synchronization issues.
3. Mobile and Single Page Applications (SPAs)
Since mobile apps and SPAs (React, Angular, Vue) cannot store session cookies like browsers, JWT provides an efficient token-based authentication mechanism.
Example: A React frontend communicating with a Spring Boot backend over REST.
4. Third-Party Authentication (OAuth2/OpenID Connect)
OAuth2 and OpenID Connect use JWT for issuing access tokens (Google, Facebook, GitHub authentication).
Example: Logging into a web app using "Sign in with Google".
5. Reduced Load on the Server
Since JWT stores authentication details on the client-side, the server does not need to validate session data in a database, improving performance.
Avoid JWT When -
1. When We Need Easy Token Revocation
If a JWT is stolen, the attacker can use it until it expires (unless you implement a blacklist).
Alternative: Use session-based authentication (e.g., Spring Security’s default session management).
2. Short-Lived User Sessions
If users log in and out frequently, storing session state might be better than issuing and validating JWTs on every request.
3. Large Payloads / Sensitive Data
JWT tokens can get large if they contain too many claims, impacting network performance.
Solution: Keep tokens small by storing only essential information (e.g., user ID, roles).
4. Browser-Based Authentication with CSRF Protection
If we need CSRF protection (like in traditional web apps), session cookies with SameSite settings are more secure than JWT stored in local storage.
Alternative: Use HttpOnly Secure Cookies instead of JWT for authentication.
Last updated
Was this helpful?