0

I would like to make the following curl call using RestTemplate in my Spring Boot application:

curl -v --tlsv1.2 --cacert /etc/pki_service/ca/cacerts.pem --cert /etc/identity/client/certificates/client.pem -key /etc/identity/client/keys/client-key.pkcs8 https://server.com

I have gone through a similar question: Using RestTemplate to send authorization certificates and Java HTTPS client certificate authentication, but not getting concrete steps to achieve exactly the same thing.

Could anyone please help here? Thanks.

Joy
  • 4,197
  • 14
  • 61
  • 131

2 Answers2

0

Import your client.pem and client-key.pkcs8 into a java key store with openssl and java keytool like this. It is possible to use a pem cert and a pkcs8 secret key directly but that is much more difficult to use them with java system properties.

Convert your pem style cacerts to a jks called cacerts.jks. I don't know what's in your cacerts.pem but doing this is similar to the previous step.

Allow the trusting of your server cacerts for server responses as follows:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks")

Add the inclusion of the client cert in RestTemplate calls: (assuming your created jks and password are "myKeystore.jks" & "changeit" respectively)

System.setProperty("javax.net.ssl.keyStore",  "myKeystore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

Force only TLSv1.2

System.setProperty("jdk.tls.client.protocol", "TLSv1.2");

You may need to do the previous with a Java command line option ‑Djdk.tls.client.protocols="TLSv1.2"

John Williams
  • 4,252
  • 2
  • 9
  • 18
0

Starting with Spring Boot 3.1, you can configure the certificates and then apply them to the RestTemplate with a small amount of code.

Given your curl example above, you might configure an SSL bundle with the name rest in an application.yaml file like this:

spring:
  ssl:
    bundle:
      pem:
        rest:
          keystore:
            certificate: "/etc/identity/client/certificates/client.pem"
            private-key: "/etc/identity/client/keys/client-key.pkcs8"
          truststore: 
            certificate: "/etc/pki_service/ca/cacerts.pem"

With this configuration, you can create a RestTemplate bean using the SslBundle named rest:

@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate sslRestTemplate(RestTemplateBuilder builder, SslBundles sslBundles) {
        SslBundle sslBundle = sslBundles.getBundle("rest");
        return builder.rootUri("https://server.com").setSslBundle(sslBundle).build();
    }

}

See the latest Spring Boot documentation for more details.

Scott Frederick
  • 4,184
  • 19
  • 22