Able to call REST API protected with SSL (HTTPS) from Postman client, but not able to call from java code

1.1k Views Asked by At

I have a 3rd party service that I need to make a REST call to from my java application, the rest api uses a client certificate-based authentication, and for using the API the 3rd party team has provided us with .cer and .key files. When I add these .cer and .key files in postman client certificates, i am able to call the API and get a response enter image description here

However, when trying to import the client certificate in java truststore(jre/lib/security/cacert) or loading the certificate in custom ssl context and then trying to make the call from my java application using a http client gives me the following exception -

 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I, first of all, created a pkcs12 certificate (.p12) using openssl command, using the cer and the key file.

pkcs12 -export -in C:\cert\abc.cer -inkey C:\certs\abc.key -out abc.p12 -name test

then tried to import the p12 file in my java code to create a custom restTemplate -

@Configuration
public class CustomConfiguration {

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

        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(new URL("file:src/main/resources/abc.p12"), "changeit".toCharArray()).build();
        SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConFactory).build();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        return restTemplate;

    }
}

prior to this I also tried to add this p12 cert to a new java keystore (jks) file and imported it to my system's java cacert, however, i still keep getting the same PKIX path building failed error. What am I doing incorrectly?

1

There are 1 best solutions below

7
Bill Mair On

Does abc.p12 also contain intermediate and root certs?

A single source of truth, so to speak.

And the JVM itself is configured to use it as a trust store too?

-Djavax.net.ssl.trustStore=abc.p12 -Djavax.net.ssl.trustStorePassword=changeit

I ask, because the JVM isn't recognizing the root CA, and that is why it can't build the chain.