DEV Community

Cover image for Disable SSL certificate validation in Spring RestTemplate
Amit Kumar
Amit Kumar

Posted on

Disable SSL certificate validation in Spring RestTemplate

We often run into certificate issue while using Rest Template.

RestTemplate can give any of the below error if SSL certificate of the target host is not valid :

  • PKIX path building failed:

  • PKIX path building failed: unable to find valid certification path to requested target PKIX path building failed

Reasons for invalid SSL certificate could be many, including:

  1. Expired certificate
  2. Self-signed certificate
  3. Wrong host information in certificates
  4. Revoked certificate
  5. Untrusted root of certificate

How we deal with it in production and non-production environment ?

In production environment, we usually add the required certificates to our application key-store, which allows us to make the HTTPS request successfully.

In non production environments, while developing an application, we often need to disable ssl certificate validation (self-signed, expired, non trusted root, etc)
as we don’t want to go through the hassle of generating appropriate certificates and managing the key-store for testing purpose.

So, We configure RestTemplate to disable SSL validation (non-prod environment), and thus trust all kind of certificates whether valid or not in Spring Boot RestTemplate and allow http requests to the hosts without throwing exception.

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;

Note : Avoid SSL Validation for RestTemplate for development environment only.

For production environment, we must do certificate management and SSL verification as disabling SSL verification might lead to security risks.

Discussion (2)

slogic profile image
Simon Logic

This article does not cover cases when RestTemplate is created by new statement (not autowired, not passed as constructor arg) within external packages.

unniksk profile image
Unni Krishnan

When the URL is provided at runtime by a user using the UI, how do we install the certificate to the keystore?