As you might notice from my previous posts I am a big fan of Spring Framework. A few weeks back, for example, I needed to set up a REST API client to be able to test some things in our Development environment. By using Spring Boot and RestTemplate I was able to create this quickly. Unfortunately I ran into the issue that the API endpoint was using a SSL certificate that wasn’t supplied by a trusted ‘default’ CA. So in this case I wanted to switch this SSL validation of in the RestTemplate.
Fortunately I wasn’t the first one with this question. Here is how you can set up your RestTemplate without the SSL Certificate Validation:
@Autowired private RestTemplate restTemplate; @Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(csf) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); return restTemplate; }
Please note that you shouldn’t do this in code that ends up in a production environment or at least make sure you understand the consequences of this hack!
Pingback: Java Weekly, Issue 190 | Baeldung