Ignore SSL certificate validation when using Spring RestTemplate
10,526
@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;
}
Author by
Zak FST
Updated on June 07, 2022Comments
-
Zak FST almost 2 years
I am using Spring RestTemplate to make HTTPS requests, and I want to ignore SSL certificate
Here is my code to create the restTemplate request:
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);
This request works when I use the server hostname, But I get the following Exception when I use the server IP address:
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: []
-
jaco0646 over 5 yearsHave you looked at Allowing Java to use an untrusted certificate for SSL/HTTPS connection?
-
-
Christian Moen over 4 yearsPlease provide some details on why this fixes the issue.
-
bucky about 2 yearsuse: (> 4.4) implementation 'org.apache.httpcomponents:httpclient:4.5.13'