问题
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?
回答1:
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));
}
}
来源:https://stackoverflow.com/questions/49168320/feign-client-dynamic-authorization-header