Search code examples
javaspringrestrestful-urlspring-resttemplate

Spring - how to pass automatically http header between microservices


I'm having multiple microservices

1. MangerApp 
2. ProcessApp
3. DoingStuffApp
4. .....

the "MangerApp Microservices" get an Http-Request I'm looking for a way to transfer automatically some of the HTTP headers in the call, while I don't want to go over each place and do - add Headers, my HTTP headers are stored as a thread-local Map.

since I call to other microservices, with RestTemplate I have many different calls some get/post/put/etc... changing each one them and passing the header manually is not that efficient. I'm looking for a way to manage it, other than extending the RestTemplate Class now.


Solution

  • You can use a ClientHttpRequestInterceptor to achieve what you need.

    1) Create a HeaderInterceptor implementing ClientHttpRequestInterceptor. In this example it gets the Authorization and Accept headers from a ThreadLocal and propagates them:

    public class HeaderInterceptor implements ClientHttpRequestInterceptor{
    
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    
                        HttpHeaders headers = request.getHeaders();
            List<String> authorization = HeaderThreadLocal.getAuthorization()
            List<String> accept = HeaderThreadLocal.getAuthorization();
    
            headers.addAll("Authorization", authorization);
            headers.addAll("Accept", accept);
            return execution.execute(request, body);
        }
    }
    

    2) Configure your RestTemplate bean adding the header interceptor:

    restTemplate.getInterceptors().add(new HeaderInterceptor());