First I created my client JKS file using below commands:

Adding the server certs:

keytool -import -alias <server cert alias> -file <server cert> -keystore <jks file>

Adding the Client cert with Key:

keytool -import -trustcacerts -file <client certificate pem> -keypass <client key pass> -storepass <truststore pass> -keystore <jks file>

then added the code just like proposed here: How do I use an SSL client certificate with Apache HttpClient?

The SSL connection protocol here is mTLS and that is why I need to add the client certificates so that client certificate can be verified by the server during the handshake.

When I am trying to call the REST API I get following error:

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

From the suggested link I am trying to execute below code:

    private static final String KEYSTOREPATH = "keystore.jks";
    private static final String KEYSTOREPASS = "keystorepass";
    private static final String KEYPASS = "keypass";

    KeyStore readStore() throws Exception {
        try (InputStream keyStoreStream = this.getClass().getResourceAsStream(KEYSTOREPATH)) {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(keyStoreStream, KEYSTOREPASS.toCharArray());
            return keyStore;    
       }
    }

    SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(readStore(), KEYPASS.toCharArray()).build();
    HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
    HttpPost postReq = new HttpPost("REST API URL");
    <set payload>
    <set headers>
    HttpResponse response = httpClient.execute(postReq);
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    EntityUtils.consume(entity);
0

There are 0 answers