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:


@Autowired
private RestTemplate restTemplate;

@Bean
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)
                    .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    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.

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

  1. Pingback: Java Weekly, Issue 190 | Baeldung

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s