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

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

Course – LS (cat=REST) (INACTIVE)

Get started with Spring and Spring Boot, through the reference Learn Spring 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:

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 file:

# The format used for the keystore
# The path to the keystore containing the certificate
# The password used to generate the certificate
# The alias mapped to the certificate

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:

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

    private RestTemplate restTemplate;

    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: PKIX path building failed: unable to find valid certification path to requested 
target at

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 file:

#trust store location
#trust store password

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

public class CustomRestTemplateConfiguration {

    private Resource trustStore;

    private String trustStorePassword;

    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()
        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:

Course – LS (cat=REST)

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

res – REST (eBook) (cat=REST)
Inline Feedbacks
View all comments
Comments are closed on this article!