2 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
添加以下類
class NonValidatingTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
然后在 Spring 中@Configuration通過聲明新 bean 覆蓋默認(rèn)的 SSLContext
@Bean
public SSLContext sslContext() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext ctx = SSLContext.getInstance("TLS"); // or try "SSL"
ctx.init(null, new TrustManager[] { new NonValidatingTrustManager() }, null);
return ctx;
}
更新
對(duì)于測(cè)試,您創(chuàng)建單獨(dú)的配置類并將覆蓋的 SSLContext 也放在那里:
@TestConfiguration
class TestConfig {
@Bean
public SSLContext sslContext() throws Exception {
SSLContext ctx = SSLContext.getInstance("TLS"); // or try "SSL"
ctx.init(null, new TrustManager[] { new NonValidatingTrustManager() }, null);
return ctx;
}
}
并在單元測(cè)試中使用它,例如:
@SpringBootTest(classes = { TestConfig.class })
class MyTest {
...
}

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以嘗試以下代碼。我正在嘗試允許所有受信任的證書,以便您可以進(jìn)行 https 調(diào)用。
try {
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());
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslcontext, NoopHostnameVerifier.INSTANCE);
HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
}
catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new BeanCreationException("Failed to create http client for ssl connection", e);
}
添加回答
舉報(bào)