eclipse, Java, REST, Spring, Spring Boot

Bypass SSL certification with Spring RestTemplate

Recently I wanted to try out a REST call on my local computer, running my microservice locally. The service calls another microservice, in the SIT environment, that required secure HTTP s connection. As I did not have the certificate installed on my workstation, but wanted to fast test the call anyway, I had to find a way to bypass SSL certificate.

Also I just created a Spring configuration class only for the “local” profile, and overwrote the RestTemplate so, that its HttpClient in the background accepts SSL connection without certificate.

@Configuration
@Profile("local")
public class LocalDevConfiguration {

  private static final Logger logger = LoggerFactory.getLogger(LocalDevConfiguration.class);

  @Bean
  public RestTemplate restTemplate(@Autowired RestTemplateBuilder builder) {
    RestTemplate restTemplate = builder
        .setConnectTimeout(Duration.ofSeconds(5))
        .setReadTimeout(Duration.ofSeconds(5))
        .requestFactory(getRequestFactorySupplier())
        .build();

    return restTemplate;
  }

  private Supplier<ClientHttpRequestFactory> getRequestFactorySupplier() {
    return () -> {
      SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslContext());
      CloseableHttpClient httpClient = HttpClients.custom()
          .setSSLSocketFactory(csf)
          .build();

      HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
      requestFactory.setHttpClient(httpClient);
      return requestFactory;
    };
  }

  private SSLContext createSslContext() {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    try {
      return SSLContexts.custom()
          .loadTrustMaterial(null, acceptingTrustStrategy)
          .build();
    } catch (Exception e) {
      logger.error("Error creating SSLContext: {}", e);
    }
    return null;
  }
}

 

The key point of the solution is the implementation of TrustStrategy interface , which returns true for every call.

In case of your project contains the httpclient library from org.apache.httpcomponents, it is possible to use already existing implementations of TrustStrategy:

  • TrustAllStrategy
  • TrustSelfSignedStrategy

As you can see, the configuration class is only active, if the profile “local” is activated. So I just can start the service locally from Eclipse using the following option:

-Dspring.profiles.active=local

After starting the service, it is possible to use the REST function via Swagger, and it communicates with the remote service without any problem. So I can fast try out and debug my application, without needing to deploy it into the SIT system.

 

Advertisement