Search code examples
spring-bootspring-cloud-feign

FeignClient is passing on headers


I have about 10 microservices all built with Spring boot 2 using Eureka and FeignClients. My microservices use certain header values to keep track of data so when a FeignClient is used it needs to pass on certain values that are in the incoming request. So if Microservice 1 does a call to Microservice 2 it must pass on the headers from the incoming request onto microservice 2. I haven't been able to find out how I can do that. I understand their is @Header however if you have 20 FeignClients then you don't want to have to manually add the @header to all the FeignClients. Can you indicate that FeignClients must read a certain header from the incoming request and pass it on in the FeignClient?


Solution

  • You can use request interceptor in Feign.

    Example Implementation:

    Request Interceptor:

    @Component
    public class MyRequestInterceptor implements RequestInterceptor {
    
        @Override
        public void apply(RequestTemplate template) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String authorization = requestAttributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
            if(null != authorization) {
                template.header(HttpHeaders.AUTHORIZATION, authorization);
            }
        }
    
    }
    

    Bean Configuration:

    @Configuration
    public class CustomFeignConfig {
    
        @Bean
        public Contract feignContract() {
            return new feign.Contract.Default();
        }
    
        @Bean
        public MyRequestInterceptor basicAuthRequestInterceptor() {
            return new MyRequestInterceptor();
        }
    
        @Bean
        public OkHttpClient client() {
            return new OkHttpClient();
        }
    
    }