Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Baeldung's Code and Testing

I’m a software engineer with a passion for clean code, test driven development, web security and data mining. Baeldung is about all of these and more.


How to use RestTemplate with Basic Authentication in Spring

 

This article shows how to use Springs RestTemplate to consume a RESTful Service secured with Basic Authentication; the article is part of an in depth series on REST with Spring.

The REST with Spring series:

Setting up the RestTemplate in Spring

Bootstraping the RestTemplate into the Spring context can be done by simply declaring a bean for it; however, setting up the RestTemplate with Basic Authentication will require manual intervention, so instead of declaring the bean directly, a Spring FactoryBean will be used for more flexibility. This factory will create and configure the template on initialization:

@Component
public class RestTemplateFactory implements
    FactoryBean< RestTemplate >, InitializingBean{
   private RestTemplate restTemplate;
   public RestTemplate getObject(){
      return restTemplate;
   }
   public Class< RestTemplate > getObjectType(){
      return RestTemplate.class;
   }
   public boolean isSingleton(){
      return true;
   }
   public void afterPropertiesSet(){
      restTemplate = new RestTemplate(
       new HttpComponentsClientHttpRequestFactoryBasicAuth
        ( new HttpHost(host, port, protocol) );
   }
}

The host and port values should be dependent on the environment – allowing the client the flexibility to define one set of values for integration testing and another for production use. The values can be managed by the first class Spring support for properties files.

Basic Authentication for the RestTemplate

Once Basic Authentication is set up for the template, each request will be sent preemptively containing the full credentials necessary to perform the authentication process. The credentials will be encoded and will use the Authorization HTTP Header, in accordance with the specs of the Basic Authentication scheme. An example would look like this:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Manual management of the Authorization HTTP header

The process of creating the Authorization header is relatively straightforward for Basic Authentication, so it can pretty much be done manually with a few lines of code:

HttpHeaders createHeaders( String username, String password ){
   return new HttpHeaders(){
      {
         String auth = username + ":" + password;
         byte[] encodedAuth = Base64.encodeBase64( auth.getBytes() );
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }
   };
}

Then, sending a request becomes just as simple:

restTemplate.exchange
 (uri, HttpMethod.POST, new HttpEntity<T>(createHeaders(username, password)), clazz);

Automatic management of the Authorization HTTP header

Both Spring 3.0 and 3.1 have very good support for the Apache HTTP libraries:

  • Spring 3.0, the CommonsClientHttpRequestFactory integrated with the now end of lifed HttpClient 3.x
  • Spring 3.1 introduced support for the current HttpClient 4.x via HttpComponentsClientHttpRequestFactory (support added in the JIRA SPR-6180)

Let’s start setting things up with HttpClient 4 and the newly introduced support from Spring 3.1. The RestTemplate accepts the HTTP request factory in it’s constructor – allowing a factory that supports Basic Authentication to be passed into the template – so far, so good. However, using the existing HttpComponentsClientHttpRequestFactory will prove to be difficult, as the architecture of RestTemplate was designed without good support for HttpContext – an instrumental piece of the puzzle.

Fortunately this is not without a solution, but first, some details on how to do Basic Authentication with the HttpClient library itself. Doing preemptive Basic Authentication with HttpClient 4.x is a bit of a burden: the authentication info is cached and the process of setting up this authentication cache is very manual and unintuitive:

private HttpContext createHttpContext() {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return localcontext;
}
HttpResponse response = httpclient.execute
 (targetHost, new HttpGet("/"), createHttpContext());

Now, this HttpContext needs to be hooked up to the RestTemplate, so that requests created via the template can benefit from the Basic Authentication support. As mentioned before, this is not an easy as it should be – the entire HttpComponentsClientHttpRequestFactory needs to be subclassed and the createHttpContext method overridden:

public class HttpComponentsClientHttpRequestFactoryBasicAuth
 extends HttpComponentsClientHttpRequestFactory {
   HttpHost host;
   public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
      super();
      this.host= host;
   }
   protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
      return createHttpContext();
   }
   private HttpContext createHttpContext() {
      ...
   }
}

And with that, everything is in place – the RestTemplate will now be able to support the Basic Authentication scheme; a simple usage patter would be:

HttpComponentsClientHttpRequestFactory requestFactory =
 (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
DefaultHttpClient httpClient =
 (DefaultHttpClient) requestFactory.getHttpClient();
httpClient.getCredentialsProvider().setCredentials(
 new AuthScope(host, port, AuthScope.ANY_REALM),
  new UsernamePasswordCredentials("name", "pass"));

For an in depth discussion on how to secure the RESTful Service itself, check out this article.

Maven dependencies

The following Maven dependencies are required for the RestTemplate itself and for the HttpClient library:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.1.3</version>
</dependency>

Optionally, if the HTTP Authorization header is constructed manually, then an additional library is required for the encoding support:

<dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.6</version>
</dependency>

Conclusion

Although the 3.x branch of development for Apache HttpClient has reached end of life for a while now, and the Spring support for that version has been fully deprecated, much of the information that can be found on RestTemplate and security still doesn’t account for the current HttpClient 4.x releases. This article is an attempt to change that through a detailed, step by step discussion on how to set up Basic Authentication with the RestTemplate and how to use it to consume a secured RESTful Service.

For the next article, the focus will be on setting up Digest Authentication in the same way. To go beyond the code samples in the article with a production ready implementation of both the consuming side, examined here, but also the actual RESTful service, check out the REST github project.

If you read this far, you should follow me on twitter here.