Monday, April 21, 2014

Spring REST template with Basic Auth, Java 8 and Spring 4.0.3

There is a little bit change of how to use Spring 4.0.3 Rest Template to call REST service with basic authentication.

Here is the standalone Java code. It is easy to convert to Spring xml style.

import java.util.HashMap;
import java.util.Map;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/*
  Required library:
     org.springframework:spring-web:4.0.3
     org.apache.httpcomponents:httpclient:4.3.3
     commons-codec:commons-codec:1.9
 */
public class AuthRestService {
private String RELATIVE_IDENTITY_URL  = "http://xxxcompute-1.amazonaws.com:8082/service/rest/v1/identity/";

public String authenticateByEmail(final String email, final String password, final String domain)  {
RestTemplate restTemplate;
Credentials credentials;

//1. Set credentials
credentials = new UsernamePasswordCredentials("test", "test");

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials( AuthScope.ANY, credentials);

         //2. Bind credentialsProvider to httpClient
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
CloseableHttpClient httpClient = httpClientBuilder.build();

HttpComponentsClientHttpRequestFactory factory = new  
                       HttpComponentsClientHttpRequestFactory(httpClient);
 
//3. create restTemplate
restTemplate = new RestTemplate();
restTemplate.setRequestFactory(factory);

//4. restTemplate execute
String url = RELATIVE_IDENTITY_URL + "domain/{domain}/email/{email}";

Map parametersMap = new HashMap();
parametersMap.put("domain", domain);
parametersMap.put("email", email);

MultiValueMap postParams = new LinkedMultiValueMap();
postParams.add("password", password);

String xml = restTemplate.postForObject(url, postParams, String.class, parametersMap);
 
return xml;
}
}