Mar 26, 2012

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");
client.getState().setCredentials(
  new AuthScope("www.example.com", 9090, AuthScope.ANY_REALM),
  credentials);
CommonsClientHttpRequestFactory commons =
     new CommonsClientHttpRequestFactory(client);

RestTemplate template = new RestTemplate(commons);
SomeObject result = template.getForObject(
     "http://www.example.com:9090/",SomeObject.class
 );



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


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

2015 conference talks

The past 2015 has been very eventful year for me on both professional and private plan. I got married, moved to Sweden, started working f...