Security Top

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security 5:

>> CHECK OUT THE COURSE
HTTP Client Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

Table of Contents

1. Overview

In this tutorial, we'll learn how to use Spring's RestTemplate to consume a RESTful Service secured with Basic Authentication.

Once we set up Basic Authentication 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 use the Authorization HTTP Header, in accordance with the specs of the Basic Authentication scheme. An example would look like this:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Further reading:

Spring RestTemplate Error Handling

Learn how to handle errors with Spring's RestTemplate

Using the Spring RestTemplate Interceptor

Learn about using interceptors in your Spring application with the RestTemplate.

Exploring the Spring Boot TestRestTemplate

Learn how to use the new TestRestTemplate in Spring Boot to test a simple API.

2. Setting up the RestTemplate

We can bootstrap the RestTemplate into the Spring context simply by declaring a bean for it; however, setting up the RestTemplate with Basic Authentication will require manual intervention, so instead of declaring the bean directly, we'll use a Spring FactoryBean for more flexibility. This FactoryBean 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() {
        HttpHost host = new HttpHost("localhost", 8082, "http");
        restTemplate = new RestTemplate(
          new HttpComponentsClientHttpRequestFactoryBasicAuth(host));
    }
}

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.

3. Manual Management of the Authorization HTTP Header

It's fairly straightforward for us to create the Authorization header for Basic Authentication, so we can do it 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(Charset.forName("US-ASCII")) );
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }};
}

Furthermore, sending a request is just as simple:

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

4. Automatic Management of the Authorization HTTP Header

Spring 3.0 and 3.1, and now 4.x, have very good support for the Apache HTTP libraries:

  • In Spring 3.0, the CommonsClientHttpRequestFactory integrated with the now end-of-life'd HttpClient 3.x.
  • Spring 3.1 introduced support for the current HttpClient 4.x via HttpComponentsClientHttpRequestFactory (support added in the JIRA SPR-6180).
  • Spring 4.0 introduced async support via the HttpComponentsAsyncClientHttpRequestFactory.

Let's start setting things up with HttpClient 4 and Spring 4.

The RestTemplate will require an HTTP request factory that supports Basic Authentication. However, using the existing HttpComponentsClientHttpRequestFactory directly will prove to be difficult, as the architecture of RestTemplate was designed without good support for HttpContext, an instrumental piece of the puzzle. As such, we'll need to subclass HttpComponentsClientHttpRequestFactory and override the createHttpContext method:

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() {
        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
}

We built the basic authentication support in here, in the creation of the HttpContext. As we can see, it's a bit of a burden for us to do preemptive Basic Authentication with HttpClient 4.x. The authentication info is cached, and it's very manual and non-intuitive for us to set up this authentication cache.

Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a BasicAuthorizationInterceptor:

restTemplate.getInterceptors().add(
  new BasicAuthorizationInterceptor("username", "password"));

Then the request:

restTemplate.exchange(
  "http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", 
  HttpMethod.GET, null, Foo.class);

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

5. Maven Dependencies

We'll require the following Maven dependencies for the RestTemplate itself and for the HttpClient library:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.6.RELEASE</version>
</dependency>

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.3</version>
</dependency>

Optionally, if we construct the HTTP Authorization header manually, then we'll require an additional library for the encoding support:

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

We can find the newest versions in the Maven repository.

6. Conclusion

Much of the information that can be found on RestTemplate and security still doesn't account for the current HttpClient 4.x releases, even though the 3.x branch is end-of-life'd and Spring's support for that version is fully deprecated. In this article, we attempt to change that by going through a detailed, step by step discussion on how to set up Basic Authentication with the RestTemplate and use it to consume a secured REST API.

To go beyond the code samples in this article with the implementation of the consuming side and the actual RESTful Service, have a look at the project over on Github.

This is a Maven-based project, so it should be easy to import and run as is.

Security bottom

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security 5:

>> CHECK OUT THE COURSE
HTTP Client bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Security footer banner
Comments are closed on this article!