Securing Microservices with OAuth2 and JWT in Spring Boot

As microservices communicate independently, securing them becomes critical. OAuth2 and JWT (JSON Web Token) are widely adopted for secure, scalable, and stateless authentication.

This guide walks through:

  • What is OAuth2 and JWT
  • Securing Spring Boot microservices with OAuth2
  • Using JWT tokens for API access
  • Sample architecture and code setup
Securing Microservices with OAuth2 and JWT

πŸ“˜ 1. What is OAuth2 and JWT?

  • OAuth2: An authorization framework that allows secure access to protected resources via tokens.
  • JWT (JSON Web Token): A compact, URL-safe token format used to represent claims between two parties. Typically used in OAuth2 to represent the access token.

πŸ— 2. Microservice Security Architecture

πŸ”„ Architecture Flow:

  1. User authenticates with Authorization Server (e.g., Keycloak / Okta).
  2. Authorization Server issues a JWT access token.
  3. Client sends this token in HTTP headers when accessing microservices.
  4. Microservices validate the token and allow/deny access.

βš™οΈ 3. Add Required Dependencies

βœ… pom.xml

πŸ“‚ 4. Project Package Structure

πŸ”’ 5. Resource Server Configuration

βœ… SecurityConfig.java

🧾 6. application.yml Configuration

πŸ“¦ 7. JWT Token Format Example

Decoded JWT token:

πŸ§ͺ 8. Sample Controller

βœ… ProductController.java

πŸ” 9. JWT Authentication in Request

Client Call Example:

Spring Security will automatically:

  • Parse the JWT
  • Validate its signature and expiration
  • Populate the Principal with the claims

🧠 10. Role-Based Access Control (RBAC)

You can add fine-grained access control using Spring Security expressions.

πŸ“Š 11. Token Generation (Using Keycloak)

If using Keycloak:

  • Create a realm
  • Register a client (set to confidential)
  • Enable β€œAuthorization” and β€œDirect Access”
  • Use client_id, client_secret to request a token:

βœ… Conclusion

Securing microservices with OAuth2 and JWT in Spring Boot enables robust, scalable, and stateless authentication. It allows services to independently validate tokens, minimizing coupling and improving scalability.

πŸ”‘ With OAuth2 and JWT:

  • APIs are protected
  • Tokens are self-contained and verifiable
  • Authorization can be role or scope-based