Skip to content
EasyFleet.

Smarter Fleet Management

Education & Enterprise

How Spring Cloud Uses OAuth2 Security: Microservices Architecture and Token Relay

Spring Cloud secures distributed microservice architectures by integrating directly with Spring Security's native OAuth 2.0 and OpenID Connect (OIDC) capabilities. In a typical Spring Cloud deployment, an API Gateway acts as an OAuth 2...

Spring Cloud secures distributed microservice architectures by integrating directly with Spring Security's native OAuth 2.0 and OpenID Connect (OIDC) capabilities. In a typical Spring Cloud deployment, an API Gateway acts as an OAuth 2.0 Client that authenticates users against an Authorization Server, obtains JSON Web Tokens (JWTs), and uses a Token Relay mechanism to pass those tokens downstream to Resource Server microservices.

Contents

Architectural Blueprint of OAuth 2.0 in Spring Cloud

In a monolithic application, security contexts, user sessions, and authorization checks reside within a single runtime instance. Microservice architectures break this centralized model into distributed nodes running across distinct containers or servers. Securing these distributed endpoints requires a stateless, standardized token architecture. Spring Cloud achieves this by adopting the OAuth 2.0 authorization framework (RFC 6749) alongside OpenID Connect (OIDC) for identity verification.

  1. Authenticate: End User / Client App sends an authentication request to Spring Cloud Gateway (OAuth 2.0 Client).
  2. Exchange Code for Tokens: Spring Cloud Gateway (OAuth 2.0 Client) exchanges the authorization code for tokens with the Authorization Server.
  3. Forward Request with Bearer JWT: Spring Cloud Gateway (OAuth 2.0 Client) forwards the request with a Bearer JWT to Microservice A (Resource Server), which interacts with the Authorization Server for validation.
  4. Return Data: Spring Cloud Gateway (OAuth 2.0 Client) returns data to the End User / Client App.

The system operates across three primary tiers:

  1. Identity and Authorization Tier: An OAuth 2.0 Authorization Server (such as Spring Authorization Server, Keycloak, Auth0, or Okta) handles authentication, manages user identities, issues signed access tokens, and exposes JSON Web Key Sets (JWKS) for signature validation.
  2. Edge / Gateway Tier: Spring Cloud Gateway serves as the single ingress point. Configured as an OAuth 2.0 Client, it handles Authorization Code grants, manages user HTTP sessions, refreshes expired tokens, and relays the Bearer token downstream.
  3. Core Business Microservices Tier: Individual domain microservices act as OAuth 2.0 Resource Servers. They do not store user sessions or initiate authentication redirects; instead, they inspect incoming JWTs, validate cryptographic signatures against the Authorization Server's JWK set, extract authority scopes, and execute fine-grained access policies.

Architectural Evolution: Legacy vs. Modern Implementation

Understanding how Spring Cloud implements OAuth 2.0 requires recognizing a major architectural shift within the Spring ecosystem.

The Legacy Model (spring-cloud-security)

In legacy Spring Boot 1.x and early 2.x applications, developers relied heavily on the spring-cloud-starter-oauth2 and spring-cloud-security libraries. These dependencies exposed annotations such as @EnableOAuth2Sso and @EnableResourceServer. While straightforward for simple setups, this implementation tightly coupled Spring Cloud to an opinionated, early-stage Spring Security OAuth stack that became hard to maintain, lacked complete OIDC spec compliance, and was deprecated by VMware/Pivotal.

The Modern Spring Security 5+ / 6+ Model

In modern Spring Boot (version 2.7+ through 3.x) and Spring Cloud (2021.0+ through 2023+ and 2024+ releases), the dedicated spring-cloud-security repository was formally retired. All OAuth 2.0 and OIDC functionality was migrated directly into core Spring Security.

Modern Spring Cloud applications leverage standard Spring Security modules:

  • spring-boot-starter-oauth2-client: Configures applications to handle Authorization Code, Client Credentials, and Refresh Token flows.
  • spring-boot-starter-oauth2-resource-server: Configures applications to validate incoming access tokens (JWTs or opaque tokens via introspection).
  • spring-cloud-starter-gateway: Integrates reactive Spring Security to pass tokens automatically across the microservice boundary.

This consolidation ensures that Spring Cloud applications benefit directly from standard security updates, WebFlux reactive support, and modern cryptographic standards.

Spring Security OAuth2 :: causeway

Key Components in a Secured Spring Cloud Topology

  • Spring Cloud Ecosystem
    • Spring Cloud Gateway (OAuth 2.0 Client)
      • Performs Token Relay to Backend Microservices (Resource Servers).
      • Requests tokens from the Identity Provider / Authorization Server.
    • Backend Microservices (Resource Servers)
      • Receives tokens from Spring Cloud Gateway.
      • Validates keys with the Identity Provider / Authorization Server.
    • Identity Provider / Authorization Server
      • Handles token requests from Spring Cloud Gateway.
      • Provides key validation endpoints for Backend Microservices.

1. Spring Cloud Gateway as an OAuth 2.0 Client

Spring Cloud Gateway acts as the entry guard. Placing login processing at the gateway prevents microservices from redundantly managing authorization redirects and state cookies.

When an unauthenticated request hits a protected gateway route:

  • The gateway's SecurityWebFilterChain intercepts the request.
  • It redirects the browser to the Authorization Server's /oauth2/authorize endpoint.
  • Upon successful authentication, the user is redirected back to the gateway's /login/oauth2/code/{registrationId} callback URL with an authorization code.
  • The gateway exchanges this code for an access_token, refresh_token, and id_token.
  • The gateway stores the client session (in memory or via Redis using Spring Session) and responds to the browser with a standard session cookie (SESSION).

2. The Token Relay Pattern

Once the gateway authenticates the user, downstream microservices still require access to the user's identity and permissions. The Token Relay pattern solves this without requiring downstream services to re-authenticate the user.

Spring Cloud Gateway provides the built-in TokenRelayFilterFactory (referenced in route configurations as TokenRelay=). When active on a route, this filter extracts the active OAuth 2.0 Access Token from the reactive security context (ServerBearerTokenAuthenticationConverter) and attaches it as an HTTP header to the upstream request:

Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

This shields internal microservices from session handling while providing them with verified user identity data.

3. Downstream Resource Server Validation

Downstream microservices receive the Authorization: Bearer header. Configured with spring-boot-starter-oauth2-resource-server, each service independently validates the token.

Validation happens in one of two ways:

  • JWT (JSON Web Token) Decoding: The microservice fetches the public keys (JWKS) from the Authorization Server during startup or on demand. It validates the cryptographic signature, checks token expiration (exp), verifies the issuer (iss), and asserts the audience (aud). This process occurs entirely in-memory without making an HTTP call for every request.
  • Opaque Token Introspection: If tokens are non-standard opaque strings, the microservice executes a synchronous HTTP call to the Authorization Server's /oauth2/introspect endpoint to verify validity and extract claims.

Inter-Service Communication (Service-to-Service Security)

User-initiated requests are not the only traffic in a microservice network. Often, Microservice A must request data from Microservice B without a user directly triggering the call (for instance, a scheduled batch processing task or an asynchronous event handler).

For service-to-service communication, Spring Cloud leverages the OAuth 2.0 Client Credentials Grant.

Configuring AuthorizedClientManager

To authorize outbound service calls, developer stacks configure an OAuth2AuthorizedClientManager using Spring Security. This component requests a client credentials access token using an assigned client-id and client-secret.

When using Spring's WebClient, the client credentials flow can be integrated directly via an exchange filter function:

@Bean public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { ServerOAuth2AuthorizedClientExchangeFilterFunction filter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); filter.setDefaultClientRegistrationId("internal-service"); return WebClient.builder() .filter(filter) .build(); }

When Microservice A calls Microservice B using this WebClient, Spring Security automatically checks if a valid token exists in the token repository. If missing or expired, it calls the Authorization Server, obtains a machine-to-machine access token, and appends the Authorization: Bearer header to the outgoing call.

If using OpenFeign inside a Spring Cloud application, developers implement a RequestInterceptor that extracts the client credentials token from an OAuth2AuthorizedClientManager and appends it to the Feign request headers.

Implementation Comparison in Spring Cloud

Choosing the right OAuth 2.0 configuration depends on where the component sits within the network boundary. The following table highlights implementation details across different Spring Cloud roles:

Component Role Required Spring Starters Primary Security Responsibility Grant Types Managed Token Handling Strategy
API Gateway spring-cloud-starter-gateway, spring-boot-starter-oauth2-client Handles user authentication, manages session state, converts code to token authorization_code, refresh_token Stores tokens in session; forwards tokens via TokenRelay filter.
User-Facing Service spring-boot-starter-oauth2-resource-server Authorizes requests based on user claims/scopes None directly (consumes Bearer token) Decodes incoming JWTs, extracts user identity and authorities.
Background / Internal Microservice spring-boot-starter-oauth2-client, spring-boot-starter-oauth2-resource-server Validates incoming user tokens; requests service tokens for outbound calls client_credentials Obtains machine-to-machine tokens via WebClient/Feign inter-service calls.
Authorization Server spring-security-oauth2-authorization-server Authenticates users/clients, issues signed JWTs, publishes JWKS endpoints authorization_code, client_credentials, refresh_token Signs JWTs using private key; serves public key via JWKS endpoint.

Common Challenges and Best Practices

Securing microservices using Spring Cloud and OAuth 2.0 introduces operational complexities that require specific configuration patterns.

1. Spring Cloud Gateway Session Management

By default, Spring Cloud Gateway manages OAuth 2.0 client states in a reactive HTTP session (WebSession). In a multi-instance gateway deployment behind a load balancer, sticky sessions or a shared session store must be configured. Utilizing Spring Session Data Redis ensures that any gateway node can access the user's OAuth 2.0 authorization state and refresh tokens interchangeably.

2. Token Expiration and Automatic Refresh

If a user's access token expires while interacting with the system, making a downstream request with an expired Bearer token results in a 401 Unauthorized response.

Spring Cloud Gateway mitigates this when configured with spring-boot-starter-oauth2-client. The gateway's OAuth2AuthorizedClientProvider automatically checks the token's remaining lifespan. If the access token is expired (or near expiration) and a refresh token is available, the gateway requests a fresh token set from the Authorization Server before executing the downstream request via TokenRelay.

3. Claims to Authorities Mapping

By default, Spring Security Resource Server maps JWT scopes to Spring GrantedAuthorities with a SCOPE_ prefix (for example, scope read becomes authority SCOPE_read). However, enterprise applications often encode custom role hierarchies inside token claims (such as roles: ["ADMIN", "USER"]).

To map these custom claims to Spring Security's standard ROLE_ authorities, developers must configure a custom JwtAuthenticationConverter:

@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/api/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt.jwtAuthenticationConverter(customJwtAuthenticationConverter())) ); return http.build(); }

4. Distributed Key Caching (JWKS Performance)

Resource servers must validate JWT signatures using the public key exposed by the Authorization Server's JWKS endpoint (typically /.well-known/jwks.json). Spring Security automatically caches these keys in memory to minimize latency.

However, ensure the Authorization Server sets appropriate HTTP cache headers (Cache-Control) on the JWKS endpoint. If key rotation occurs on the Authorization Server, Spring Security automatically invalidates its cached keys when it encounters a JWT with an unrecognized Key ID (kid).

Frequently Asked Questions

Why not validate JWTs directly at the API Gateway and strip the token before forwarding?

Stripping tokens at the gateway converts downstream microservices into unauthenticated, open internal endpoints. If an attacker bypasses the gateway or accesses the internal network directly, services become vulnerable. Retaining the token via Token Relay maintains a Zero Trust architecture: every microservice verifies authenticity independently.

How does Spring Cloud handle OAuth 2.0 in reactive (WebFlux) vs. servlet applications?

Spring Cloud Gateway is built natively on Spring WebFlux (reactive stack). Consequently, gateway security configurations must use reactive components such as ServerHttpSecurity, ReactiveSecurityContextHolder, and ReactiveOAuth2AuthorizedClientManager. Downstream microservices can use either standard MVC Servlets (HttpSecurity) or reactive WebFlux depending on their specific runtime framework.

Is Spring Authorization Server required to use OAuth 2.0 with Spring Cloud?

No. Spring Cloud adheres to standard RFC-compliant OAuth 2.0 and OIDC specifications. You can use any compliant Authorization Server, including Keycloak, Auth0, Okta, Ping Identity, or Azure AD (Entra ID). As long as the identity provider exposes standard metadata (/.well-known/openid-configuration) and JWKS endpoints, Spring Cloud integrates seamlessly.

How do microservices propagate security contexts during asynchronous event messaging?

Token Relay applies to synchronous HTTP/REST communications via Spring Cloud Gateway or HTTP clients. For asynchronous messaging architectures (e.g., using Spring Cloud Stream with Kafka or RabbitMQ), HTTP Bearer tokens are not automatically relayed. In those cases, developers extract the JWT from the current SecurityContext, attach it as a custom header in the message metadata, and re-establish the SecurityContext inside the message consumer.

Next Steps and Recommendations

To implement robust OAuth 2.0 security across your Spring Cloud architecture:

  1. Centralize Authentication at the Gateway: Configure Spring Cloud Gateway as your OAuth 2.0 Client using spring-boot-starter-oauth2-client to keep login redirects and session state out of your business microservices.
  2. Apply the Token Relay Filter: Enable TokenRelay= on protected gateway routes so valid Bearer tokens are automatically attached to downstream requests.
  3. Configure Stateless Resource Servers: Ensure backend microservices use spring-boot-starter-oauth2-resource-server and validate JWTs locally via JWKS to minimize authentication overhead.
  4. Implement Client Credentials for Internal Calls: Use WebClient configured with ReactiveOAuth2AuthorizedClientManager to secure inter-service communication without forwarding user tokens where inappropriate.
  5. Enforce Distributed Session Storage: Deploy Spring Session Data Redis at the gateway tier to preserve user authorization state across horizontally scaled gateway instances.

Written by

Phillip Dawson

Executive Productivity & Operations Editor

You Might Also Like

View All