How to to trust all certificates in a spring boot project

344 views Asked by At

I have created the following configuration class in order to trust all certificates in my spring boot project:

package com.nttdata.iplanet.hubject.utils;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

@Configuration
public class TrustAllCertificatesConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder()
                .requestFactory(this::trustAllCertificatesRequestFactory)
                .build();
    }

    private ClientHttpRequestFactory trustAllCertificatesRequestFactory() {
        TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {}

            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {}

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }};

        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException("Failed to initialize SSLContext", e);
        }

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

        // Utilizzare una versione di HttpComponentsClientHttpRequestFactory compatibile
        // con la versione delle librerie Apache HTTP Client che stai utilizzando.

        // Versione per Apache HTTP Client 4.5.x:
        // return new HttpComponentsClientHttpRequestFactory(httpClient);

        // Versione per Apache HTTP Client 4.3.x:
        return new HttpComponentsClientHttpRequestFactory(httpClient);

    }
}

But I receive error in the last raw of my code, that is:

return new HttpComponentsClientHttpRequestFactory(httpClient);

and I can't understand why.

The dependency that I used on my pom.xml is:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>

How Can I solve it??

1

There are 1 answers

3
Aloysius Tri Sulistyo Putranto On

This Code Running Well in my Project

    public void getAllCertificatePermit() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
            public void checkClientTrusted(X509Certificate[] certs, String authType) { }
            public void checkServerTrusted(X509Certificate[] certs, String authType) { }
        } };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) { return true; }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }

And Call it

public ResponseEntity<String> hitApi(String url, String bodyJson) {
try {
    // for HTTPS
    getAllCertificatePermit();
    var restTemplate = new RestTemplate();

    var header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_JSON);
    header.setBasicAuth("Set Token");
    header.set("apiKey", "Set Api Key");
    HttpEntity<String> request = new HttpEntity<>(bodyJson, header);

    return restTemplate.exchange(url, HttpMethod.POST, request, String.class);
}catch (Exception e){
    log.error(Arrays.toString(e.getStackTrace())));
    return null;
    }
  }