Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sat Oct 29 2022

Disable SSL certificate validation in RestTemplate in Spring Boot

A short guide on how to disable certification checks in Java using Spring Boot and RestTemplate. This can be handy when you have two systems inside of the same network that is not required to have certificate validation, but you still need the validation since the API might be exposed outside of the network.

In this guide, we will setup a simple helper class that will disable the checks, and then use it when firing requests.

Create a CertificateHelper class

In our CertificateHelper class, add following code

package com.example; import lombok.extern.slf4j.Slf4j; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.security.cert.X509Certificate; @Slf4j public class CertificateHelper { public static void ignoreCertificates() { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } }}; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { log.error("Issues setting up certificates. " + e.getMessage()); } } }

Consume it

And now, in our method where we are calling the endpoints using RestTemplates for example, we call it like below:

public <T> T get(String url, HttpHeaders headers, Class<T> classType) { CertificateHelper.ignoreCertificates(); RestTemplate template = new RestTemplate(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); ResponseEntity<T> entity = template.exchange(url, HttpMethod.GET, requestEntity, classType); return entity.getBody(); }

And that's how we ignore the SSL certificate validation.

Outro

That's it for this short guide, I hope you found this helpful and leave an email at our contact us page if you need further input.

All the best,

signatureSat Oct 29 2022
See all our articles