In Spring Boot I'm trying to create a RestTemplate which will use basic authentication using
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
builder.basicAuthorization("username", "password");
RestTemplate template = builder.build();
return template;
}
I then inject the RestTemplate in my service class as
@Autowired
private RestTemplate restTemplate;
However, my requests fail with a 401 unauthorized exception:
Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
Using another REST Client (Postman) the requests to the same URL succeeds so I assume the basic authentication is not working correctly. From the debug output it looks as if the authentication header is not being set. What will make this work?
The problem is that you are using the
RestTemplateBuilder
in a wrong way. TheRestTemplateBuilder
is immutable. So when doingbuilder.basicAuthorization("username", "password")
you actually get a new instance, with aBasicAuthorizationInterceptor
added and configured, of theRestTemplateBuilder
. (this applies to all configuration methods of theRestTemplateBuilder
they all create a fresh copied instance).However your code is discarding that specifically configured instance and you are basically using the non secured default
RestTemplateBuilder
.This code should be replaced with something like this.
Which will use the specifically configured instance.
One solution is to create the RestTemplate as follows: