Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Partner – Frontegg – expanded (cat = Security)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Partner – Frontegg – expanded (cat = Spring Security)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Automation Job Top
We’re looking for a Backend Java/Spring Developer with Integration Experience: Read More
NPI – Security Top – Temp – Non-Geo (Frontegg)

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
NPI – Frontegg – Security – (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

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:

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);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConFactory).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:

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.

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
REST bottom

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

>> CHECK OUT THE COURSE
REST footer banner
guest
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments