Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY
Course – LS (cat=REST)

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

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll see how to consume a REST service secured with HTTPS using Spring’s RestTemplate.

2. Setup

We know that to secure a REST service, we need a certificate and a keystore generated from a certificate. We can get certificates from Certification Authorities (CA) to ensure that the application is secure and trusted for production-grade applications.

For this article’s purpose, we’ll use a self-signed certificate in our sample application.

We’ll use Spring’s RestTemplate to consume an HTTPS REST service.

First, let’s create a controller class, WelcomeController, and a /welcome endpoint which returns a simple String response:

@RestController
public class WelcomeController {

    @GetMapping(value = "/welcome")
    public String welcome() {
       return "Welcome To Secured REST Service";
    }
}

Then, let’s add our keystore in the src/main/resources folder:

secure cert resource folder

Next, let’s add keystore-related properties to our application.properties file:

server.port=8443
server.servlet.context-path=/
# The format used for the keystore
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/baeldung.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=baeldung

We can now access the REST service at this endpoint: https://localhost:8443/welcome

3. Consuming Secured REST Service

Spring provides a convenient RestTemplate class to consume REST services.

While it’s straightforward to consume a simple REST service, when consuming a secured one, we need to customize the RestTemplate with the certificate/keystore used by the service.

Next, let’s create a simple RestTemplate object and customize it by adding the required certificate/keystore.

3.1. Create a RestTemplate Client

Let’s write a simple controller that uses a RestTemplate to consume our REST service:

@RestController
public class RestTemplateClientController {
    private static final String WELCOME_URL = "https://localhost:8443/welcome";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/welcomeclient")
    public String greetMessage() {
        String response = restTemplate.getForObject(WELCOME_URL, String.class);
        return response;
    }
}

If we run our code and access the /welcomeclient endpoint, we’ll get an error since a valid certificate to access the secured REST Service won’t be found:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested 
target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

Next, we’ll see how to resolve this error.

3.2. Configuring the RestTemplate for HTTPS Access

The client application accessing the secured REST service should contain a secure keystore in its resources folder. Further, the RestTemplate itself needs to be configured.

First, let’s add the keystore baeldung.p12 from earlier as the truststore in the /src/main/resources folder:

Keystore in resource folder

Next, we need to add the truststore details in the application.properties file:

server.port=8082
#trust store location
trust.store=classpath:keystore/baeldung.p12
#trust store password
trust.store.password=password

Finally, let’s customize the RestTemplate by adding the truststore:

@Configuration
public class CustomRestTemplateConfiguration {

    @Value("${trust.store}")
    private Resource trustStore;

    @Value("${trust.store.password}")
    private String trustStorePassword;

    @Bean
    public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, MalformedURLException, IOException {

        SSLContext sslContext = new SSLContextBuilder()
         .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
        SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext);
        HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(sslConFactory)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(requestFactory);
    }
}

Let’s understand the important steps in restTemplate() method above in detail.

First, we create an SSLContext object that represents a secure socket protocol implementation. We use the SSLContextBuilder class’s build() method to create it.

We use the SSLContextBuilder‘s loadTrustMaterial() method to load the keystore file and credentials into the SSLContext object.

Then, we create SSLConnectionSocketFactory, a layered socket factory for TSL and SSL connections, by loading SSLContext. The purpose of this step is to verify that the server is using the list of trusted certificates we loaded in the previous step, i.e., to authenticate the server.

Now we can use our customized RestTemplate to consume secured REST service at the endpoint: http://localhost:8082/welcomeclient:
Secured Rest Service By Customized Rest template Response

4. Conclusion

In this article, we discussed how to consume a secured REST service using a customized RestTemplate.

As always, the source code is available over on GitHub.

Course – LSS (cat=Security/Spring Security)

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

>> CHECK OUT THE COURSE
Course – LS (cat=REST)

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

>> CHECK OUT THE COURSE
res – REST (eBook) (cat=REST)
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.