Small hack to avoid SSL validation in Spring RestTemplate

As you might notice from my previous posts I am a big fan of Spring Framework. A few weeks back, for example, I needed to set up a REST API client to be able to test some things in our Development environment. By using Spring Boot and RestTemplate I was able to create this quickly. Unfortunately I ran into the issue that the API endpoint was using a SSL certificate that wasn’t supplied by a trusted ‘default’ CA. So in this case I wanted to switch this SSL validation of in the RestTemplate.

Fortunately I wasn’t the first one with this question. Here is how you can set up your RestTemplate without the SSL Certificate Validation:

private RestTemplate restTemplate;

public RestTemplate restTemplate() 
                throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;

Please note that you shouldn’t do this in code that ends up in a production environment or at least make sure you understand the consequences of this hack!


About Pascal Alma

Pascal is a senior IT consultant and has been working in IT since 1997. He is monitoring the latest development in new technologies (Mobile, Cloud, Big Data) closely and particularly interested in Java open source tool stacks, cloud related technologies like AWS and mobile development like building iOS apps with Swift. Specialties: Java/JEE/Spring Amazon AWS API/REST Big Data Continuous Delivery Swift/iOS
This entry was posted in Security, Spring Framework and tagged , . Bookmark the permalink.

1 Response to Small hack to avoid SSL validation in Spring RestTemplate

  1. Pingback: Java Weekly, Issue 190 | Baeldung

Comments are closed.