How Will You Implement Authentication and Authorization Across Multiple Microservices?
Authentication and authorization are very important in microservices architecture.
In large systems:
- Many microservices exist
- Multiple users access APIs
- Services communicate internally
- Sensitive business data flows across network
Without proper security:
- Unauthorized users may access APIs
- Data leakage may occur
- Internal services may be attacked
- Financial fraud may happen
Authentication vs Authorization
| Concept | Meaning |
|---|---|
| Authentication | Who are you? |
| Authorization | What can you access? |
Real-Time Banking Example
Mobile Banking App
↓
API Gateway
↓
Account Service
Payment Service
Transaction Service
Loan Service
Requirements
- User must login securely
- Only valid users should access APIs
- Admin users should have extra permissions
- Services should trust authenticated requests
- Internal services should also be secured
Production-Level Security Architecture
Client ↓ API Gateway ↓ Authentication Server ↓ JWT Token ↓ Microservices
Common Production Technologies
- JWT
- OAuth2
- OpenID Connect (OIDC)
- Keycloak
- Spring Security
- API Gateway
- mTLS
- RBAC
Step 1: Centralized Authentication Server
Never implement login separately in every microservice.
Wrong Approach
Order Service Login Payment Service Login Account Service Login
Problems
- Duplicate code
- Difficult maintenance
- Inconsistent security
Correct Approach
Single Authentication Server
Popular Authentication Servers
- Keycloak
- Okta
- Auth0
- Microsoft Azure AD
Benefits
- Centralized authentication
- Easy token management
- Single Sign-On (SSO)
- Improved security
Step 2: Use JWT Tokens
JWT (JSON Web Token) is commonly used in microservices.
JWT Flow
User Login
↓
Auth Server Validates Credentials
↓
JWT Token Generated
↓
Client Sends JWT to APIs
JWT Structure
Header.Payload.Signature
JWT Payload Example
{
"sub": "user123",
"role": "ADMIN",
"exp": 1711111111
}
Benefits
- Stateless authentication
- Scalable
- No session storage required
Step 3: API Gateway Authentication
API Gateway acts as security entry point.
Flow
Client ↓ JWT API Gateway ↓ Microservices
Gateway Responsibilities
- Validate JWT
- Authenticate users
- Rate limiting
- Request filtering
- Security enforcement
Spring Cloud Gateway Example
spring:
cloud:
gateway:
default-filters:
- TokenRelay
Benefits
- Centralized security
- Reduced duplication
- Better maintainability
Step 4: Secure Microservices Using Spring Security
Each microservice should validate JWT independently.
Why?
Never fully trust external systems.
Spring Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth ->
auth
.requestMatchers("/admin/**")
.hasRole("ADMIN")
.anyRequest()
.authenticated()
)
.oauth2ResourceServer(
oauth -> oauth.jwt()
);
return http.build();
}
}
Benefits
- Secure APIs
- Role validation
- Independent protection
Step 5: Implement Authorization Using Roles
Authorization controls what users can access.
Real Banking Example
| Role | Access |
|---|---|
| CUSTOMER | View own account |
| ADMIN | Manage all accounts |
| MANAGER | Approve loans |
Spring Security Role Example
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/accounts")
public List<Account> getAccounts() {
return service.findAll();
}
Benefits
- Controlled access
- Prevents unauthorized actions
- Improves security
Step 6: Service-to-Service Authentication
Internal microservices should also authenticate each other.
Problem Without Internal Security
Any service can call Payment Service
Production Solution
- JWT between services
- mTLS
- OAuth2 Client Credentials Flow
OAuth2 Client Credentials Flow
Service A
↓
Auth Server
↓ Access Token
Service B
Benefits
- Secure internal communication
- Prevents fake service access
Step 7: Use mTLS for Internal Security
mTLS verifies both services.
How It Works
Service A ↔ Certificate Validation ↔ Service B
Benefits
- Strong service identity
- Encrypted traffic
- Prevents service spoofing
Step 8: Token Propagation
JWT token should propagate across services.
Example
User ↓ JWT Order Service ↓ JWT Payment Service
Benefits
- End-to-end identity tracking
- Consistent authorization
Feign Client Token Forwarding Example
@Bean
public RequestInterceptor requestInterceptor() {
return template -> {
String token = getToken();
template.header(
"Authorization",
"Bearer " + token
);
};
}
Step 9: Secrets Management
Never hardcode passwords or tokens.
Bad Practice
password=admin123
Production Solutions
- HashiCorp Vault
- Amazon Web Services Secrets Manager
- Kubernetes Secrets
- Azure Key Vault
Benefits
- Secure credential storage
- Centralized management
- Easy rotation
Step 10: Use RBAC (Role-Based Access Control)
Every service should have minimum permissions.
Example
Notification Service Cannot Access Payment Database
Benefits
- Least privilege principle
- Reduced attack surface
Step 11: Logging and Monitoring
Monitor authentication and authorization events.
Monitor
- Failed logins
- Unauthorized access attempts
- Token expiration
- Suspicious API usage
Monitoring Tools
- Grafana
- Prometheus
- ELK Stack
- Splunk
Distributed Tracing
Track authenticated requests across services.
Tools
- Jaeger
- Zipkin
Real Production Incident
Issue
A fintech application exposed internal APIs without authorization validation.
Impact
- Unauthorized data access
- Internal API misuse
- Security compliance violations
Root Causes
- No centralized authentication
- No JWT validation
- No RBAC
- Hardcoded credentials
Fixes Applied
- Implemented Keycloak
- Enabled JWT authentication
- Secured APIs using Spring Security
- Added RBAC authorization
- Enabled mTLS internally
- Introduced Vault for secrets
Final Result
Before: Weak authentication and authorization After: Centralized and secure access control across all microservices
Production Best Practices
| Technique | Purpose |
|---|---|
| JWT | Stateless authentication |
| OAuth2 | Secure authorization |
| API Gateway | Centralized security |
| Spring Security | Secure APIs |
| RBAC | Role-based authorization |
| mTLS | Secure internal communication |
| Secrets Management | Secure credentials |
| Monitoring | Security visibility |
Final Interview Answer
To implement authentication and authorization across multiple microservices, I would use a centralized authentication server such as Keycloak with OAuth2 and JWT tokens. Users authenticate once and receive a JWT token, which is validated by the API Gateway and individual microservices using Spring Security. For authorization, I would implement RBAC using roles and permissions. Internal microservice communication would also be secured using JWT propagation or mTLS. Additionally, I would use API Gateway for centralized security enforcement, Vault for secrets management, and monitoring tools to track unauthorized access and security events in production environments.