Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my RestTemplate ClientHttpRequestInterceptor not called?

I want to use interceptor to add authorization header to every request made via rest template. I am doing it like this:

public FirebaseCloudMessagingRestTemplate(@Autowired RestTemplateBuilder builder, @Value("fcm.server-key") String serverKey) {
    builder.additionalInterceptors(new ClientHttpRequestInterceptor() {
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().add("Authorization", "key=" + serverKey);
            System.out.println(request.getHeaders());
            return execution.execute(request, body);
        }
    });
    this.restTemplate = builder.build();
}

However when I do this

  DownstreamHttpMessageResponse response = restTemplate.postForObject(SEND_ENDPOINT, request, DownstreamHttpMessageResponse.class);

Interceptor is not called (Iv put breakpoint in it and it did not fire). Request is made and obvious missing auth key response is returned. Why is my interceptor not called?

like image 582
Antoniossss Avatar asked Jan 04 '23 07:01

Antoniossss


1 Answers

Ok I know whats happening. After checking build() implementation I discovered that RestTemplateBuilder is not changing self state when calling additionalInterceptors but returns a new builder with given interceptors. Chaining calls solves the issue.

public FirebaseCloudMessagingRestTemplate(final @Autowired RestTemplateBuilder builder, final @Value("${fcm.server-key}") String serverKey) {
    this.restTemplate = builder.additionalInterceptors((request, body, execution) -> {
        request.getHeaders().add("Authorization", "key=" + serverKey);
        log.debug("Adding authorization header");
        return execution.execute(request, body);
    }).build();
}
like image 69
Antoniossss Avatar answered May 14 '23 04:05

Antoniossss