Search code examples
springspring-bootapiresttemplatehttp-status-code-403

Spring RestTemplate: 403 Exception (sometimes)


I have a RestTemplate call to an API (get). This call, is the only we have of GET type, and go through a proxy. It seems that sometimes during a week, the call returns a 403 Forbidden with this exception: "sun.security.validator.ValidatorException"

We have a certificate between Spring and the API, but the certificate works fine (the application returns thousands of "200 ok" during a day).

But sometimes, only this call (not others that are POST) returns a "403 Forbidden".

We have done:

  • Launch Jmeter with curl through the proxy (everything seems ok)
  • Disable the TrustStore only to test (the result is ko)

This is the RestTemplate code:

SSLConnectionSocketFactory socketFactory;
socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder()
    .loadTrustMaterial(ResourceUtils.getFile(this.trustStorePath), this.trustStorePassword.toCharArray())
    .loadKeyMaterial(ResourceUtils.getFile(this.keyStorePath), this.keystorePassword.toCharArray(),
        this.keystorePassword.toCharArray())
    .build(), NoopHostnameVerifier.INSTANCE);


CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(host)
    .disableCookieManagement().disableRedirectHandling().build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);

RestTemplate restTemplateVar = new RestTemplate(requestFactory);

And this is the call:

response = this.restTemplate.getForEntity(this.host, String.class);
  • Could the number of concurrent connections be the cause?
  • Why only with GET and sometimes?
  • And the last one: If we change RestTemplate by Httpconnection, the result could be different?

Thank in advance


Solution

  • Setting this properties works fine (it depends on your metrics)

    .setMaxConnTotal(1000)
    .setMaxConnPerRoute(40)

    CloseableHttpClient client = HttpClients.custom()
    .setSSLSocketFactory(socketFactory)
    .setProxy(host)
    .disableCookieManagement()
    .disableRedirectHandling()
    .setMaxConnTotal(1000)        
    .setMaxConnPerRoute(40)
    .build();