Search code examples
javaspring-bootsslresttemplate

How to disable SSL for given url or for restTemplateBuilder?


I need to disable the SSL for a given url or for the restTemplate right know i can disable all the SSL's with the code bellow. How can i make this code for given URL only. Or how to disable it for the restTemplate.

 public class SSLTool {

            public static void disableCertificateValidation() {
                // Create a trust manager that does not validate certificate chains
                        TrustManager[] trustAllCerts = new TrustManager[] {
                                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                                                return new X509Certificate[0];
                                            }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }};
        
                        // Ignore differences between given hostname and certificate hostname
                                HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) { return true; }
        };
        
                        // Install the all-trusting trust manager
                                try {
                        SSLContext sc = SSLContext.getInstance("SSL");
                        sc.init(null, trustAllCerts, new SecureRandom());
                        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                        HttpsURLConnection.setDefaultHostnameVerifier(hv);
                    } catch (Exception e) {/* intentionally left blank */}
            }
}

Solution

  • I solved this with the following code down below. here is the link to the source https://stackoverflow.com/a/42689331/16529288

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