If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

The new Certification Class of Learn Spring Security is out:

>> CHECK OUT THE COURSE

1. Overview

This article will show how to configure the Spring RestTemplate to consume a service secured with Digest Authentication.

Similar to Basic Authentication, once Digest auth is set in the template, the client will be able to go through the necessary security steps and get the information needed for the Authorization header:

Authorization: Digest 
    username="user1",
    realm="Custom Realm Name",
    nonce="MTM3NTYwOTA5NjU3OTo5YmIyMjgwNTFlMjdhMTA1MWM3OTMyMWYyNDY2MGFlZA==",
    uri="/spring-security-rest-digest-auth/api/foos/1", 
    ....

With this data, the server can correctly authenticate the request and return the 200 OK response.

2. Setup the RestTemplate

The RestTemplate needs to be declared as a bean in the Spring context – this is simple enough either in XML or plain Java, using the @Bean annotation:

import org.apache.http.HttpHost;
import org.baeldung.client.HttpComponentsClientHttpRequestFactoryDigestAuth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ClientConfig {

    @Bean
    public RestTemplate restTemplate() {
        HttpHost host = new HttpHost("localhost", 8080, "http");
        CloseableHttpClient client = HttpClientBuilder.create().
          setDefaultCredentialsProvider(provider()).useSystemProperties().build();
        HttpComponentsClientHttpRequestFactory requestFactory = 
          new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client);

        return new RestTemplate(requestFactory);;
    }
    
    private CredentialsProvider provider() {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = 
          new UsernamePasswordCredentials("user1", "user1Pass";
        provider.setCredentials(AuthScope.ANY, credentials);
        return provider;
    }
}

Most of the configuration of the digest access mechanism is done in the custom implementation of the client http request factory injected into the template – HttpComponentsClientHttpRequestFactoryDigestAuth.

Note that we are now pre-configuring the template with the credentials that have access to the secured API.

3. Configure Digest Authentication

We are going to leverage the support introduced in Spring 3.1 for the current HttpClient 4.x – namely the HttpComponentsClientHttpRequestFactory – by extending and configuring it.

We’re mainly going to configure the HttpContext and hook up our custom logic for Digest Authentication:

import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

public class HttpComponentsClientHttpRequestFactoryDigestAuth 
  extends HttpComponentsClientHttpRequestFactory {

    HttpHost host;

    public HttpComponentsClientHttpRequestFactoryDigestAuth(HttpHost host) {
        super(httpClient);
        this.host = host;
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        return createHttpContext();
    }

    private HttpContext createHttpContext() {
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local auth cache
        DigestScheme digestAuth = new DigestScheme();
        // If we already know the realm name
        digestAuth.overrideParamter("realm", "Custom Realm Name");
        authCache.put(host, digestAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
}

Now, the RestTemplate can simply be injected and used in a test:

@Test
public void whenSecuredRestApiIsConsumed_then200OK() {
    String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1";
    ResponseEntity<Foo> entity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class);
    System.out.println(entity.getStatusCode());
}

To illustrate the full configuration process, this test also sets up the user credentials – user1 and user1Pass. This part should, of course, be done only once and outside the test itself.

4. Maven dependencies

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

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

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

5. Conclusion

This tutorial showed how to set up and configure the Rest Template so that it can consume an application secured with Digest authentication. The REST API itself needs to be configured with the digest security mechanism.

The implementation can be found in the example GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

Go deeper into Spring Security with the course:

>> LEARN SPRING SECURITY

Sort by:   newest | oldest | most voted
Alxll
Guest

Is in’t DefaultHttpClient deprecated now? And requestFactory.getHttpClient() returns InternalHttpClient which is not compatibe with DefaultHttpClient?

Eugen Paraschiv
Guest

Hey Aixii – thanks for the heads up – I updated the code samples – let me know if everything work OK for you know. Cheers,
Eugen.

Fran Serrano
Guest

Can it be that you’re missing a parameter on the factory’s constructor with the HttpClient? Shouldn’t you pass it to the parent with super(client);?

Eugen Paraschiv
Guest

It most definitely is – nice catch. I was passing it in the code (on github) but I missed it in the article – thanks. It should be sorted now. Cheers,
Eugen.

Sayali
Guest

Could you please update readme for this project? I am not understanding what steps need to follow in order to run the project.. Please help.

Eugen Paraschiv
Guest

Sure thing Sayali – what are you having problems with exactly? Cheers,
Eugen.

wpDiscuz