How is JWT Used in Microservices?
JWT (JSON Web Token) is widely used in Microservices Architecture for authentication and authorization.
In microservices, multiple independent services communicate with each other. JWT helps securely identify users and validate requests without maintaining server-side sessions.
JWT enables:
- Stateless authentication
- Secure API communication
- User identity verification
- Role-based authorization
- Scalable authentication systems
What is JWT?
JWT stands for JSON Web Token.
It is a compact, secure, and digitally signed token used for transmitting user information between systems.
JWT usually contains:
- User identity
- User roles
- Expiration time
- Security signature
Structure of JWT
JWT contains three parts:
Header.Payload.Signature
1. Header
Contains token type and signing algorithm.
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload
Contains user information and claims.
{
"sub": "naresh@gmail.com",
"role": "ADMIN",
"exp": 1756789200
}
3. Signature
Used to verify token authenticity.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secretKey )
Why JWT is Used in Microservices
In Microservices Architecture:
- Many services exist
- Requests pass through multiple services
- Authentication must work across all services
JWT provides centralized and stateless authentication.
Problem Without JWT
Suppose an application contains:
- Auth Service
- Course Service
- Payment Service
- Interview Service
Without JWT:
- Every service maintains separate session
- Session synchronization becomes difficult
- Scalability decreases
- Distributed authentication becomes complex
How JWT Solves the Problem
Auth Service generates JWT after successful login.
The token is sent with every request.
Each microservice validates the token independently.
JWT Authentication Flow in Microservices
User Login
|
v
Auth Service
|
v
Generate JWT Token
|
v
Client Stores Token
|
v
Client Sends Token with Requests
|
v
API Gateway / Microservices Validate JWT
Real-Time Example
Suppose a user logs into an online learning platform.
Services
- Auth Service
- Course Service
- Payment Service
- Interview Service
Step 1: User Login
POST /login
{
"email": "naresh@gmail.com",
"password": "password123"
}
Step 2: Auth Service Validates Credentials
If credentials are correct:
- JWT token is generated
Step 3: JWT Token Generated
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiJuYXJlc2hAZ21haWwuY29tIiwicm9sZSI6IlVTRVIifQ . signature
Step 4: Client Stores JWT
JWT can be stored:
- HTTP-only cookies
- Memory storage
- Secure storage
Step 5: Client Sends JWT with Requests
Authorization: Bearer JWT_TOKEN
Step 6: API Gateway Validates Token
API Gateway checks:
- Token validity
- Signature
- Expiration
- User roles
Step 7: Request Forwarded to Services
Client | v API Gateway | ------------------------------------------- | | | v v v Course Service Payment Service Interview Service
Services trust the validated JWT.
How JWT Works Internally
1. User Authentication
Auth Service verifies username and password.
2. Token Generation
JWT token is generated using secret key.
3. Token Signing
Signature ensures token integrity.
4. Token Validation
Every service validates:
- Signature
- Expiration time
- User roles
JWT Architecture in Microservices
Client
|
v
API Gateway
|
v
Validate JWT
|
---------------------------------------------------
| | |
v v v
Course Service Payment Service Interview Service
JWT with API Gateway
Usually JWT validation happens at API Gateway level.
Advantages
- Centralized authentication
- Reduced duplicate logic
- Improved security
JWT Claims
Claims contain user-related information.
Common Claims
| Claim | Description |
|---|---|
| sub | User identifier |
| role | User role |
| exp | Expiration time |
| iat | Issued time |
Spring Boot JWT Example
JWT Dependency
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
Generate JWT Token
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(
new Date(System.currentTimeMillis()
+ 1000 * 60 * 60)
)
.signWith(
Keys.hmacShaKeyFor(secretKey.getBytes()),
SignatureAlgorithm.HS256
)
.compact();
}
Validate JWT Token
public boolean validateToken(String token) {
Jwts.parserBuilder()
.setSigningKey(secretKey.getBytes())
.build()
.parseClaimsJws(token);
return true;
}
JWT Filter Example
String authHeader =
request.getHeader("Authorization");
if(authHeader != null &&
authHeader.startsWith("Bearer ")) {
String token =
authHeader.substring(7);
jwtService.validateToken(token);
}
Advantages of JWT in Microservices
1. Stateless Authentication
No server-side session storage required.
2. Scalability
JWT works efficiently in distributed systems.
3. Independent Validation
Every microservice can validate JWT independently.
4. Reduced Database Calls
Services do not need database lookup for every request.
5. Better Performance
Token validation is fast.
Challenges of JWT in Microservices
1. Token Revocation
Once issued, JWT remains valid until expiration.
2. Token Size
Large payloads increase request size.
3. Security Risks
Improper storage may expose tokens.
4. Expiration Management
Short expiration improves security but requires refresh tokens.
JWT Best Practices
- Use HTTPS always
- Use short expiration time
- Store tokens securely
- Use refresh tokens
- Never store sensitive data inside JWT
- Use strong secret keys
JWT vs Session Authentication
| Feature | JWT | Session Authentication |
|---|---|---|
| State Management | Stateless | Stateful |
| Scalability | Better | Limited |
| Server Storage | Not required | Required |
| Microservices Support | Excellent | Complex |
JWT with Refresh Token
Short-lived access tokens improve security.
Refresh tokens help generate new access tokens.
Flow
Login | v Access Token + Refresh Token | v Access Token Expires | v Refresh Token Generates New Access Token
Real-Time Company Example
Netflix and Amazon use token-based authentication systems in distributed microservices environments.
JWT-like mechanisms help:
- Authenticate millions of users
- Secure APIs
- Support scalable distributed systems
Interview Ready Answer
JWT (JSON Web Token) is used in Microservices Architecture for stateless authentication and authorization. After successful login, Auth Service generates a JWT token containing user information and roles. The client sends the token with every request, and microservices validate the token independently without maintaining server-side sessions. JWT improves scalability, performance, and security in distributed systems and is commonly used with API Gateway, Spring Security, OAuth2, and Spring Boot microservices.
Frequently Asked Questions
Why is JWT preferred in microservices?
Because JWT supports stateless and scalable authentication across distributed services.
Where is JWT validated?
Usually at API Gateway or inside individual microservices.
Can JWT work without sessions?
Yes. JWT is stateless and does not require server-side session storage.
Why are refresh tokens used?
Refresh tokens generate new access tokens after expiration without forcing users to login again.
Is JWT secure?
Yes, when used properly with HTTPS, strong secret keys, short expiration, and secure storage.