2

I have a service that gets http request with an authorization header. When processing the request, I want to use a Feign Client to query another service. The query to the other service should include the same authorization header.

Currently I use a Filter to extract the authorization header from the incoming request, store the header in a ThreadLocal. When building the Feign Client I use a RequestInterceptor to read the authorization header from the ThreadLocal and put it into the request to the other service.

This approach is not ideal, because when I start using things like RxJava or Hystrix, threads are changed while processing the request and I have to move the authorization header ThreadLocal from one thread to another.

What are other options to solve this? One way that I am thinking about is to create a new FeignClient for each request, this way I would no longer need to store the authorization in a thread local. But is this a good idea?

D-rk
  • 5,513
  • 1
  • 37
  • 55

1 Answers1

8

I think I found a solution for my problem. Using RequestContextHolder I can get a reference to the original request (also from spawned child threads) and copy the header from there:

public class AuthForwardInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
    }
}
D-rk
  • 5,513
  • 1
  • 37
  • 55
  • Works perfectly! Just in case, I don't know if it is necessary to add @Component annotation on top of " public class AuthForwardInterceptor implements RequestInterceptor". Also, this is what I needed to import: import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import feign.RequestInterceptor; import feign.RequestTemplate; – Carlos Cruz Sep 29 '20 at 00:03