使用Spring RestTemplate时忽略SSL证书验证

3
我正在使用Spring RestTemplate进行HTTPS请求,并希望忽略SSL证书。
以下是创建restTemplate请求的代码:
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String 
authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new 
SSLConnectionSocketFactory(sslContext);
loseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
...
response = restTemplate.exchange("https://192.168.1.2:/foo/bar", 
HttpMethod.POST, entity,String.class);

当我使用服务器主机名时,此请求有效,但是当我使用服务器IP地址时,出现以下异常:

Exception in thread "main" 
org.springframework.web.client.ResourceAccessException: I/O error on POST 
request for "https://192.168.1.2/foo/bar": Certificate for 
<192.168.1.2> doesn't match any of the subject alternative names: []; 
nested exception is javax.net.ssl.SSLPeerUnverifiedException: Certificate 
for <192.168.1.2> doesn't match any of the subject alternative names: []

Caused by: javax.net.ssl.SSLPeerUnverifiedException: Certificate for 
<192.168.1.2> doesn't match any of the subject alternative names: []

1个回答

7
@Bean
public RestTemplate restTemplate() throws GeneralSecurityException {

    TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();

    BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
            socketFactoryRegistry);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setConnectionManager(connectionManager).build();

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(requestFactory);

    return restTemplate;
}

2
请提供一些详细信息,说明为什么这个修复方案可以解决问题。 - Christian Moen
使用:(> 4.4)实现'org.apache.httpcomponents:httpclient:4.5.13' - bucky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接