How to use SSL Cert in Java Code in Azure App Service

1.6k Views Asked by At

I am trying to call a back-end API from Java Client which uses SSL authentication. For .Net there is a snippet available on how to achieve this on MS documentation, but don't have any for Java.

I have added the Application Settings - WEBSITE_LOAD_CERTIFICATES with my Private Cert Thumbprint and WEBSITE_LOAD_USER_PROFILE=1

I have tried to connect the dots and ended up with the below code but i am getting error:

      KeyStore ks;
      ks = KeyStore.getInstance("Windows-MY");
      ks.load(null, null); 
      Certificate cert = ks.getCertificate("<subject-cn>");
      TrustManagerFactory trustManagerFactory = 
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
      trustManagerFactory.init(ks);
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
      SSLSocketFactory factory = sslContext.getSocketFactory();
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setSSLSocketFactory(factory);
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");

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

What is wrong in the above code? Is there any documentation on how this can be achieved ?

0

There are 0 best solutions below