如何信任Spring Boot项目中的所有证书

How to to trust all certificates in a spring boot project

提问人:guido pastore 提问时间:11/14/2023 更新时间:11/15/2023 访问量:54

问:

我创建了以下配置类,以便信任我的Spring Boot项目中的所有证书:

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

    }
}

但是我在代码的最后一个原始文件中收到错误,即:

返回 new HttpComponentsClientHttpRequestFactory(httpClient);

我不明白为什么。

我在pom.xml上使用的依赖项是:

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

我该如何解决??

java spring-boot ssl-certificate 信任

评论

0赞 user207421 11/15/2023
您收到什么错误?

答:

-1赞 Aloysius Tri Sulistyo Putranto 11/14/2023 #1

这段代码在我的项目中运行良好

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

并称它为”

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

评论

0赞 guido pastore 11/14/2023
我想在使用 feignClient 时信任所有证书。我该怎么办?
0赞 Aloysius Tri Sulistyo Putranto 11/15/2023
让我先试试,如果我得到了它,我会分享,但我认为如果使用 okHttp,它根本没有区别
0赞 user207421 11/15/2023
getAcceptedIssuers()可能不会返回 null。