Basic Authentication with RestTemplate

Spring Rest Templates are very good way of writing REST clients. By default they work with basic HTTP so if we need to use Basic Authorization we would need to init the rest template with custom HttpClient. This way the Rest Template will automatically use Basic Auth and append to the HTTP headers "Authorization: Basic BASE64ENCODED_USER_PASS".

HttpClient client = new HttpClient();
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials("USERNAME","PASS");
  new AuthScope("", 9090, AuthScope.ANY_REALM),
CommonsClientHttpRequestFactory commons =
     new CommonsClientHttpRequestFactory(client);

RestTemplate template = new RestTemplate(commons);
SomeObject result = template.getForObject(

In EE application this would probably be managed by DI framework like Spring Core and only initialized once since  RestTemplate is stateless.

HTTP Basic Auth
Spring Rest Templates
Spring Rest Templates JavaDoc
Apache HTTP components

Popular Posts