I am trying to call a 2-way-auth thirdparty POST api using a certificate and its working in a basic java project, below is the code to create the socket factory instance before using that in the POST call. Now the problem is as soon as I move the code in the java web application (tomcat 8.5) it does not work and give 401, exact same code, is there anything specific need to be setup in the tomcat ? Any pointer will help. Thank you !
private static SSLContext getSSLSocketFactory() throws Exception {
SSLContext context = null;
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream keyInput = new FileInputStream(new File("certificate-1.pfx"));
keyStore.load(keyInput, PFX_Password.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, PFX_Password.toCharArray());
context = SSLContext.getInstance("TLSv1.3");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context;
}
Most likely the issue is in how you load the file. However, if that's the case, you should normally get an
IOExceptionduring thekeyStore.load()call, but as you said you don't observe any errors in the logs. You could double-check if your code swallows this exception somewhere up the call stack, or if you write your application logs to some specific location.Assuming you bundle your application as a WAR file, your
certificate-1.pfxfile should end up in theWEB-INF/classesfolder. The way to ensure this depends on your build system, but if you use Maven, you just need to put the file into thesrc/main/resourcesfolder of your sources.Then you can get this file as a stream as follows: