Feign Client - Dynamic Authorization Header

你。 提交于 2019-12-11 12:49:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!