Security in Java Microservices
Microservices expand the attack surface of applications. Each service needs authentication, authorization, encrypted communication, and secure configuration — especially critical for finance and healthcare systems in the US, UK, and Australia.
Security Challenges in Microservices
- Many network endpoints to protect.
- Service-to-service communication must be authenticated.
- Distributed sessions don't work — use stateless JWT tokens.
- Secrets and credentials must not be hardcoded.
- Each service may have different access control requirements.
OAuth 2.0 and JWT
OAuth 2.0 delegates authorization to an identity provider (Auth0, Keycloak, Azure AD). JWT (JSON Web Tokens) carries signed claims about the user. API gateways validate JWTs before forwarding requests to microservices.
Spring Security with JWT
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}
}Defense in Depth
API Gateway
Single entry point for auth, rate limiting, and routing.
mTLS
Mutual TLS encrypts service-to-service communication.
Secrets Management
HashiCorp Vault or cloud secret managers for credentials.
Network Policies
Kubernetes network policies restrict pod-to-pod traffic.
Frequently Asked Questions
Should each microservice validate JWT?▼
Yes. Never trust network boundaries alone. Each service should validate the JWT signature and check authorization claims for the resources it owns.
