A. Hafid
A. Hafid

Reputation: 489

Spring RestTemplate certificate 403 Forbidden: [no body]

I use p12 certificate with RestTemplate to call an external API.

RestTemplate:

final SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(keyStoreFile.getURL(), keyPassword.toCharArray(), (X509Certificate[] chain, String authType) -> true)
                    .build();
            final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, INSTANCE);

            final HttpClient httpClient = custom()
                    .setSSLSocketFactory(socketFactory)
                    .setMaxConnTotal(1000)
                    .setMaxConnPerRoute(40)
                    .build();

            final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

            restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(requestFactory));

And the call:

HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
final ResponseEntity<MyList> response = restTemplate.exchange("https://REMOTE_URI/sameObjects", GET, entity, MyList.class);

I tried header with differents values (User-Agent, Host, ..) and ResponseEntity<Object> , but I have always the same error :

org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: [no body]

I can access it with Postman with the p12 certificate.

Thank you for your help

Upvotes: 0

Views: 6294

Answers (1)

A. Hafid
A. Hafid

Reputation: 489

I found the solution, I change RestTemplate :

  public RestTemplate getRestTemplate() {

        try {
            final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(keyStoreFile.getInputStream(), keyPassword.toCharArray());


            final SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(keyStoreFile.getURL(), keyPassword.toCharArray(), (X509Certificate[] chain, String authType) -> true)
                    .loadKeyMaterial(keyStore, keyPassword.toCharArray())
                    .build();
            final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, INSTANCE);

            final HttpClient httpClient = custom()
                    .setSSLSocketFactory(socketFactory)
                    .build();

            final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

            final RestTemplate restTemplate = new RestTemplate();
            restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(requestFactory));

            return restTemplate;
        } catch (IOException e) {
            log.error("....", e);
            throw new ApiException(e);
        } catch (Exception e) {
            log.error("....", e);
            throw new ApiException(e);
        }
    }

Upvotes: 1

Related Questions