2 回答
TA贡献2039条经验 获得超7个赞
添加以下类
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 覆盖默认的 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;
}
更新
对于测试,您创建单独的配置类并将覆盖的 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;
}
}
并在单元测试中使用它,例如:
@SpringBootTest(classes = { TestConfig.class })
class MyTest {
...
}
TA贡献1851条经验 获得超4个赞
您可以尝试以下代码。我正在尝试允许所有受信任的证书,以便您可以进行 https 调用。
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);
}
添加回答
举报