Spring Boot RestTemplate Basic Authentication using RestTemplateBuilder

Viewed 15416

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?

2 Answers
Related