Skip to content

Instantly share code, notes, and snippets.

@javajack
Created January 1, 2020 06:43
Show Gist options
  • Save javajack/047d7b1c2af21e6f3abcbded5995d59b to your computer and use it in GitHub Desktop.
Save javajack/047d7b1c2af21e6f3abcbded5995d59b to your computer and use it in GitHub Desktop.
RestTemplate IgnoreSSL And Self Signed Certificates ~ Not For Production
/*
* Create a RestTemplate bean
* with trust all SSL certificates and SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
* replaced for new apache httpclient to NoopHostnameVerifier.INSTANCE
*/
@Bean
public RestTemplate restTemplate() throws NoSuchAlgorithmException, KeyManagementException {
/*
* Ignore untrusted certificates
*/
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
/*
* Create an HttpClient that uses the custom SSLContext and do not verify cert hostname
*/
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
HttpComponentsClientHttpRequestFactory customRequestFactory
= new HttpComponentsClientHttpRequestFactory();
customRequestFactory.setHttpClient(httpClient);
/*
* Create a RestTemplate that uses custom request factory
*/
return new RestTemplate(customRequestFactory);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment