javaspring-bootsslapache-httpclient-5.x

Skip SSL certificate verification in Spring Rest Template - Spring Boot 3.x.x


How can I skip SSL certificate verification in Spring Rest Template with Spring Boot 3? I am finding lots of solutions online and on Stack Overflow which are compatible with Spring Boot 2.x.x but don't work with Spring Boot 3.x.x

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);

This code gives compilation error in Spring Boot 3.


Solution

  • You can try something like this to create the HTTP client:

    import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
    import org.apache.hc.client5.http.impl.classic.HttpClients;
    import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
    import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
    import org.apache.hc.client5.http.ssl.TrustAllStrategy;
    import org.apache.hc.core5.ssl.SSLContexts;
    
    [...]
    
    private CloseableHttpClient getHttpClient()
          throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        return HttpClients.custom()
            .setConnectionManager(
                PoolingHttpClientConnectionManagerBuilder.create()
                    .setSSLSocketFactory(
                        SSLConnectionSocketFactoryBuilder.create()
                            .setSslContext(
                                SSLContexts.custom()
                                    .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
                                    .build())
                            .setHostnameVerifier((s, sslSession) -> true)
                            .build())
                    .build())
            .build();
      }
    
    [...]
    

    Obviously you shouldn't use this in production as it's completely insecure.