How to add p12 client certificate to your REST Template in Spring boot ?
Here is the simple steps to add your client certificate (p12) to your rest template in spring boot project. So that all the consequence REST calls can be made with the client certificate secure way.
Configuring REST Template with client certificate p12 Example code
Add the below snippet to your main spring boot application class where @SpringBootApplication is added or your void main class.
@Bean public RestTemplate restTemplate() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(ResourceUtils.getFile("classpath:clientCertificate.p12")),"default".toCharArray()); SSLConnectionFactory sslConnectionFactory = new SSLConnectionFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(keystore, "default".toCharArray()).build(),NoopHostnameVerifier.INSTANCE ); HttpClient httpClient = HttpClient.custom().setSSLSocketFactory(socketFactory).build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); return restTemplate; }
Need multiple rest template ?
Do you communicate with multiple systems and only few systems requires client certificate needs to be send in every request, then you need to configure / add one more rest template for the other use cases and auto wire it using @Qualifier.
@Bean("plainRestTemplate") public RestTemplate plainRestTemplate(){ return new RestTemplate(); }
Now you can add the required rest template either using only @Autowired or @Autowired with @Qualifier
Make sure to keep your clientCertificate.p12 inside your src/main/resources folder.