Backend Development 7 min read

Implementing Token Relay in Spring Cloud with OpenFeign and RequestContextHolder

This article explains how to achieve token relay across microservice calls in Spring Cloud by manually propagating JWT tokens using OpenFeign, addressing challenges with circuit breaker sub‑threads, and leveraging RequestContextHolder with InheritableThreadLocal, accompanied by complete Java code examples.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Implementing Token Relay in Spring Cloud with OpenFeign and RequestContextHolder

Hello everyone, I am Chen, and this is the 20th article in the "Spring Cloud Advanced" series.

Today we discuss how to ensure that JWT tokens are not lost during microservice calls, a feature officially called Token Relay .

What is Token Relay?

Token Relay simply means passing the token along the microservice call chain so that each service can obtain the user information contained in the token.

Consider an order scenario: the client sends a request with a token to the gateway; after successful authentication, the gateway extracts the user information from the token and forwards it in the request header to the Order Service, which in turn passes the information to the Account Service to retrieve the user's account details.

The challenge is how to guarantee that the user information is propagated through the chain gateway → order service → account service .

Solution

During an OpenFeign call the token is not automatically relayed, so it must be manually transferred.

Note: When circuit‑breaker fallback is enabled, OpenFeign executes the internal call in a child thread, making the traditional approach of setting the token in a RequestInterceptor ineffective.

How can a child thread still obtain the request header information? The answer is the magical RequestContextHolder .

RequestContextHolder stores request attributes using InheritableThreadLocal , allowing child threads to share the same data.

In the class FeignCircuitBreakerInvocationHandler there is a line:

RequestContextHolder.setRequestAttributes(requestAttributes);

Thus, to implement token relay we only need to read the information from RequestContextHolder and add it to the Feign request.

Below is the complete implementation:

/**
 * @author 公众号:码猿技术专栏
 * 用于实现令牌信息中继
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // 从 RequestContextHolder 中获取 HttpServletRequest
        HttpServletRequest httpServletRequest = RequestContextUtils.getRequest();
        // 获取 RequestContextHolder 中的 Header 信息
        Map
headers = getHeaders(httpServletRequest);
        // 放入 Feign 的 RequestTemplate 中
        for (Map.Entry
entry : headers.entrySet()) {
            template.header(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 获取原请求头
     */
    private Map
getHeaders(HttpServletRequest request) {
        Map
map = new LinkedHashMap<>();
        Enumeration
enumeration = request.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }
}

The source code directory is shown below:

Source code has been uploaded to GitHub. Follow the public account 码猿技术专栏 and reply with the keyword 9529 to obtain it!

Final Note (Please support)

Each article is carefully crafted. I have compiled three series into PDFs. You can get them by following the public account and replying with the corresponding keywords:

Spring Cloud Advanced – reply Spring Cloud 进阶

Spring Boot Advanced – reply Spring Boot进阶

Mybatis Advanced – reply Mybatis 进阶

If this article helped you, please like, view, share, and bookmark – your support is my biggest motivation!

Follow the public account 码猿技术专栏 for more resources and join the discussion group by replying 加群 .

JavaMicroservicesSpring CloudOpenFeignRequestContextHolderToken Relay
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.