Victor Soares
Victor Soares

Reputation: 882

Java - How to propagate the Headers to Spring OpenFeign

I have a microservice that calls several micro services in cascade, using FeignClient (spring cloud). I want to propagate all the header values between then, without declare one atribute per header value at the feign method.

There is a way to do that? I was not able to find that online.

Sample of the propagation of headers that I have:

void doSomething(Long id, 
    @Header("Accept-Language") String language, 
    @Header("Accept") accept, 
    @Header("Authorization") authorization, 
    @Header("Connection") connection, ...)

Upvotes: 0

Views: 2658

Answers (1)

geobreze
geobreze

Reputation: 2422

Here is an example of how you can do it with RequestInterceptor

@Component
class CurrentRequestHeadersInterceptor implements RequestInterceptor {
  @Override
  public void apply(RequestTemplate template) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
      HttpServletRequest webRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
      webRequest.getHeaderNames().asIterator()
          .forEachRemaining(h -> template.header(h, webRequest.getHeader(h)));
    }
  }
}

As for AnnotatedParameterProcessor, I found a way to add only one header from the request, but I don't think this will work for you.

If you prefer explicit header passing, you can use @RequestHeader annotation to pass headers as Map.

@FeignClient(name = "test", url = "localhost:9090")
interface TestClient {
  @RequestMapping("/test")
  void test(@RequestHeader Map<String, List<String>> headers);
}

Then you can add WebRequest as your controller's method parameter, convert a request to a Map of headers and then pass it to the client.

Upvotes: 1

Related Questions