Skip to content
Solar Account.
Education & Software

Implementing the Spring Cloud Security Token Relay Pattern for Microservices

The Spring Cloud Security Token Relay pattern is a design mechanism used in microservices architectures to pass an OAuth2 access token from a gateway or edge service to downstream resource services. It ensures that the user's identity and permissions are prese...

Implementing the Spring Cloud Security Token Relay Pattern for Microservices

The Spring Cloud Security Token Relay pattern is a design mechanism used in microservices architectures to pass an OAuth2 access token from a gateway or edge service to downstream resource services. It ensures that the user's identity and permissions are preserved across service boundaries without requiring multiple logins or complex re-authentication logic.

Contents

In modern distributed systems, securing communication between services is as critical as securing the initial user entry point. As of 2026, the industry has standardized on the Token Relay pattern as the primary method for maintaining stateless authentication across complex microservice meshes. By utilizing Spring Cloud Gateway and Spring Security, developers can implement a seamless flow where a bearer token, once obtained by the client, is automatically injected into outbound requests to internal services. This pattern effectively solves the problem of identity propagation, allowing each downstream microservice to act as a Resource Server that can independently verify the user's claims and authorize actions based on the provided token.

Understanding the Role of Token Relay in Modern Architectures

The core of the Token Relay pattern lies in the concept of delegation. When a user interacts with a frontend application, they typically authenticate against an Identity Provider (IdP) like Keycloak, Okta, or Auth0. Once the frontend receives an access token, it sends that token to the backend API. In a microservices environment, that API is often a Gateway.

The Gateway acts as the "OAuth2 Client." Its job is not just to route traffic but to manage the security context. Without a Token Relay, the Gateway would strip the security headers or require the downstream services to somehow know who the user is through non-standard means. The Token Relay pattern formalizes this by ensuring that the Authorization: Bearer header is extracted from the incoming request (or the authorized client session) and appended to the outgoing request directed at the target microservice.

By 2026, this pattern has evolved to support not only standard JWTs (JSON Web Tokens) but also opaque tokens that are exchanged for JWTs at the gateway level. This provides an additional layer of security, as internal service details remain hidden from the public internet while internal services still benefit from the rich claims provided by a JWT.

How to Secure your REST APIs with Spring Security & JSON Web Tokens (JWTs)

Core Prerequisites and Architecture Requirements

Before implementing the Token Relay pattern, several infrastructure components must be in place to ensure a secure and functional environment.

  1. Identity Provider (IdP): A centralized server that supports OpenID Connect (OIDC) and OAuth 2.1 protocols. This server issues the tokens that will be relayed.
  2. Spring Cloud Gateway: This serves as the entry point for all requests. It must be configured as an OAuth2 Client to handle the initial token acquisition or validation.
  3. Downstream Resource Servers: These are your individual microservices (e.g., Order Service, User Service). They must be configured as OAuth2 Resource Servers so they can decode and validate the incoming relayed tokens.
  4. Shared Security Configuration: Consistency is vital. All services must trust the same IdP and, in the case of JWTs, must have access to the same public keys (usually via a JWK Set URI) to verify the token signatures.

In a production-grade 2026 environment, it is also recommended to use Mutual TLS (mTLS) in conjunction with Token Relay. While the token identifies the user, mTLS identifies the service-to-service connection, providing a "defense-in-depth" strategy that protects against token theft within the internal network.

How the Token Relay Pattern Works in Spring Cloud Gateway

The implementation in Spring Cloud depends heavily on the TokenRelayGatewayFilterFactory. This component is a specialized filter provided by the Spring Cloud Starter Gateway library. When a route is configured with this filter, the Gateway performs a specific sequence of actions for every request matching that route.

First, the Gateway looks for an authenticated user in its own security context. If the user is authenticated via OAuth2, the Gateway retrieves the OAuth2AuthorizedClient associated with that session. This object contains the access token, refresh token, and other metadata. The filter then extracts the access token and places it into the header of the request it is about to send downstream.

What makes this pattern powerful is its "set and forget" nature. Once the filter is applied to a route, developers do not need to manually write code to handle headers or manage token lifetimes for each service call. The Gateway handles the complexity of refreshing tokens (if configured) and ensuring that the most current valid token is always passed forward.

Configuration and Implementation Guidelines

Implementing the Token Relay pattern does not require extensive custom Java code. Instead, it relies on precise configuration within your application.yml or application.properties files.

To begin, the Gateway project must include the dependencies for spring-cloud-starter-gateway and spring-boot-starter-oauth2-client. These provide the necessary classes for both routing and security management.

Gateway Configuration

In the configuration file, you must define your OAuth2 client registrations. This includes specifying the provider, client-id, client-secret, and scope. Under the Spring Cloud Gateway route definitions, you must explicitly add the TokenRelay filter.

For example, a route targeting an internal "inventory-service" would specify the URI of that service and, in its list of filters, include the TokenRelay entry. This tells the Gateway that any request routed to the inventory service must carry the user's access token. If you are using a standard OIDC flow, you should also ensure that the gateway property for spring.security.oauth2.client.registration is correctly mapped to your IdP's issuer URI.

Downstream Service Configuration

The microservice receiving the token must be prepared to handle it. This service requires the spring-boot-starter-oauth2-resource-server dependency. Its configuration is simpler: it primarily needs the jwk-set-uri from the Identity Provider. This allows the service to download the public keys required to verify that the token was indeed signed by the trusted IdP and has not been tampered with.

Comparison of Token Propagation Strategies

While Token Relay is the standard, other strategies exist. Understanding the differences helps in choosing the right tool for specific security requirements.

Strategy Mechanism Best Use Case Security Level
Token Relay Gateway passes user's JWT to downstream services. Standard microservices, UI-to-Backend flows. High (User identity preserved)
Client Credentials Gateway uses its own identity to call downstream services. System-to-system tasks, background jobs. Medium (Lacks user context)
Basic Auth Gateway passes static credentials to downstream. Legacy systems, internal non-sensitive tools. Low (Hard to rotate)
Opaque to JWT Gateway exchanges an opaque handle for a full JWT internally. High-security environments, hiding PII from clients. Very High (Privacy focused)
BFF Pattern Backend-for-Frontend manages sessions; no token on client. Web applications requiring strict cookie security. High (Prevents XSS/CSRF)

Security Best Practices and Common Pitfalls

Even with a robust pattern like Token Relay, several common mistakes can compromise the security of a 2026-era microservices ecosystem.

Token Exposure: Never relay tokens to external third-party APIs unless they are part of your trusted circle. The Token Relay filter should be applied selectively to internal routes. If an external API requires a token, use a separate Client Credentials flow specifically for that integration.

Scope Management: Ensure that the tokens issued have the appropriate "scopes." A token relayed to a "Read-Only" service should ideally not have "Write" permissions. While the Token Relay pattern passes the whole token, the downstream Resource Server is responsible for checking these scopes before executing business logic.

Clock Skew: Distributed systems often suffer from minor time differences between servers. If your Gateway's clock is ahead of your Resource Server's clock, a newly issued token might be rejected as "not yet valid." Configure a small "clock skew" (e.g., 30 to 60 seconds) in your Resource Server's JWT decoder to prevent intermittent authentication failures.

Sensitive Data in JWTs: Since JWTs are relayed across multiple services, avoid putting highly sensitive information (like passwords or unencrypted PII) in the claims. While the token is signed, it is often not encrypted, meaning any service in the chain can read the content.

Troubleshooting Token Relay Issues

When the Token Relay pattern fails, it usually manifests as a 401 Unauthorized or 403 Forbidden error at the downstream service level. Troubleshooting should follow a logical path from the edge to the interior.

First, verify that the Gateway is actually receiving the token. You can use logging to inspect the incoming headers. If the Gateway does not have an active security context, the TokenRelay filter will have no token to pass, often resulting in an empty Authorization header downstream.

Second, check the logs of the downstream Resource Server. If it receives the token but rejects it, the log will often specify why. Common reasons include an expired token, an invalid issuer (iss) claim, or an unreachable JWK Set URI. In 2026, many developers use "Discovery" URLs for OIDC; ensure the Gateway and all Resource Servers can resolve the DNS of the Identity Provider.

Finally, verify the "Audience" (aud) claim. Some Identity Providers issue tokens for a specific audience. If the downstream service expects an audience claim of "inventory-api" but the token was issued for "gateway-client," the validation will fail. You may need to configure your IdP to include all microservice IDs in the audience list or configure the Resource Servers to be less restrictive about the audience claim.

Advanced Considerations for 2026 Architectures

As we move through 2026, the Token Relay pattern is increasingly being integrated with Service Meshes like Istio or Linkerd. In these environments, the "relay" logic can sometimes be moved out of the application code and into the sidecar proxy. However, the Spring Cloud Security implementation remains the preferred choice for developers who want "application-aware" security where the code can easily access user details (like Principal or Authentication objects) without relying solely on the infrastructure layer.

Furthermore, the rise of OAuth 2.1 has deprecated the Implicit Grant. This means that Token Relay implementation almost exclusively uses the Authorization Code Flow with PKCE (Proof Key for Code Exchange). When setting up your Gateway, ensure that PKCE is enabled to protect against authorization code injection attacks, especially if your client-side application is a Single Page Application (SPA) or mobile app.

FAQ

What happens if the token expires during a long-running request?

The Token Relay pattern typically passes the token that was valid at the start of the request. If the token expires mid-process, the downstream service will reject the call. To mitigate this, Spring Cloud Gateway can be configured to use a ReactiveOAuth2AuthorizedClientManager that checks token validity and refreshes the token before it is relayed, provided a refresh token is available in the session.

Does Token Relay work with WebSockets?

Token Relay with WebSockets is more complex because the initial handshake is HTTP, but subsequent communication is over a persistent connection. While the initial upgrade request can relay the token, maintaining and rotating tokens over a long-lived WebSocket connection requires custom implementation, such as sending "token update" frames from the client to the gateway.

Can I use Token Relay without Spring Cloud Gateway?

Yes, the pattern is a conceptual one. You can implement it manually in a Zuul proxy (though Zuul is largely deprecated in 2026) or even in a standard Spring Boot application using RestTemplate or WebClient interceptors. However, Spring Cloud Gateway provides the most streamlined, "out-of-the-box" experience for this pattern.

How does Token Relay affect performance?

The performance impact is generally negligible. The Gateway must perform a lookup in its authorized client repository (often in-memory or Redis), which is very fast. The primary overhead comes from the downstream service needing to validate the JWT signature, which can be optimized by caching the JWK (JSON Web Key) locally so it doesn't have to call the IdP for every request.

Is it possible to relay multiple tokens?

Standard Token Relay handles one primary access token. If your architecture requires multiple tokens (for example, a user token and a separate service-identity token), you would need to implement a custom filter that extracts multiple headers or combines claims. This is rarely necessary and often indicates a need to simplify the security architecture.

Optimal Implementation Path

To successfully deploy the Spring Cloud Security Token Relay pattern, start by securing a single route between your Gateway and one microservice. Use a tool like JWT.io to inspect the tokens being generated by your Identity Provider to ensure they contain the expected claims. Once the first link is verified, you can scale the configuration across your entire service mesh.

Always prioritize using WebClient for internal service-to-service calls if you are working within the reactive stack of Spring Cloud Gateway. The integration between WebClient and Spring Security's ServerOAuth2AuthorizedClientExchangeFilterFunction provides a robust programmatic alternative to the Gateway filter for cases where one microservice needs to call another while acting as the user.

Written by

Andrew Miller

Personal Finance & Banking Reporter