I'm currently trying to write a Spring Boot starter that would automatically authenticate our microservices with an API gateway and include the access token in the headers for all outgoing requests (towards the gateway).
I'm creating a RestTemplate bean and giving it our custom interceptor, but my problem is, by doing this, I prevent other teams (who would be using this starter) to use their own RestTemplate config, since they would have to define the same bean leading to multiple beans existing.
@Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if (interceptors.isEmpty()){ interceptors = new ArrayList<>(); } interceptors.add(clientCredentialsAuthInterceptor()); restTemplate.setInterceptors(interceptors); return restTemplate; } Is there another way of intercepting all outgoing requests or make the RestTemplate further configurable?
RestTemplateBuilderto create instances of aRestTEmplatethis in turn will auto detect all pre-registered interceptors. The only thing your autp-config has to do is make a bean for the interceptor. Or define aRestTemplateCustomizerwhich adds the interceptor. However this only works if teams follow the practice of using theRestTemplateBuilderto create instances.