I\'m building two java applications which have to communicate using SSL two way authentication, I used instructions from here to create client and server certificates.
then
For anyone looking to implement 2 way mutual auth, following code worked perfectly for me.
FileInputStream keystoreInputStream = null;
FileInputStream truststoreInputStream = null;
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystoreInputStream = new FileInputStream("C:\\Users\\Aman\\STSProj\\AppSecurity\\clientkeystore.p12");
keystore.load(keystoreInputStream, "client".toCharArray());
keystoreInputStream.close();
KeyStore trustore = KeyStore.getInstance(KeyStore.getDefaultType());
truststoreInputStream = new FileInputStream("C:\\Users\\Aman\\STSProj\\AppSecurity\\clienttruststore.p12");
trustore.load(truststoreInputStream, "client".toCharArray());
SSLContext sslcontext = SSLContexts.custom().useProtocol("TLS")
.loadKeyMaterial(keystore, "client".toCharArray())
.loadTrustMaterial(trustore, null).build();
HostnameVerifier hostnameverifier = null;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
null, null, hostnameverifier);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemp = new RestTemplate(requestFactory);
String greetings = restTemp
.getForObject("https://localhost:8443/SecureAppServer/test/security/hello/aman123", String.class);
System.out.println("Received greetings from secured server ---> " + greetings);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (keystoreInputStream != null) {
try {
keystoreInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (truststoreInputStream != null) {
try {
truststoreInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}