I need to remove WebFlux dependencies from one of our repos. When I switch from WebClient to RestTemplate, I get 403 errors, invalid authorization.
The original code:
return webClient.post()
.uri(String.join("/", jobConfig.getBaseUrl(), JOB_RUN_NOW_PATH))
.header(HttpHeaders.AUTHORIZATION, jobConfig.getAccessToken())
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(BodyInserters.fromValue(jobBody))
.exchangeToMono(this::handleResponse);
...
private Mono<JobResponseBody> handleResponse(ClientResponse clientResponse) {
return clientResponse.bodyToMono(JobResponseBody.class);
}
webClient instantiation:
@Bean
public WebClient webClient(WebClient.Builder builder) {
return builder.build();
}
The new code:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HttpHeaders.AUTHORIZATION, jobConfig.getAccessToken());
HttpEntity<JobRequestBody> request = new HttpEntity<>(jobBody, headers);
return restTemplate.exchange(
String.join("/", jobConfig.getBaseUrl(), JOB_RUN_NOW_PATH),
HttpMethod.POST,
request,
JobResponseBody.class
).getBody();
restTemplate instantiation:
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder().build();
}
When I run the WebClient code, I receive a successful response. When I run the RestTemplate code, I receive a 403 Invalid access token error. I have verified that the token in both cases is in the correct form. I am using Spring Boot 2.6.7. The authorization tokens are in the format "Bearer dapic..." as confirmed by inspection in debugging mode. The url is also the same. I am calling an actual external service in the integration test.
How do I successfully pass authorization in RestTemplate?