Saturday, 28 January 2017

Spring Resttemplate with SSL Http Client

Using Spring Bean XML version

Below Configuration for beans will inject the Spring Restemplate bean with the appropriate SSL.

     <beans:bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"   id="requestFactory">
        <beans:property name="httpClient" ref="httpClient">
    </beans:property></beans:bean>

    <beans:bean class="com.test.HttpClientBuilderBean" id="httpClient">

    <beans:bean class="org.springframework.web.client.RestTemplate" id="restTemplate">
        <beans:property name="requestFactory" ref="requestFactory"></beans:property>
    </beans:bean>

       </beans:bean>

Create a custom class to generate the httpClient Bean like below . Use previous post for sslSocketFactoryBean

  public class HttpClientBuilderBean implements FactoryBean<HttpClient>  {
 @Autowired
 private MySSLSocketFactory mySSLSocketFactoryBean;
 private static final Logger LOGGER = Logger.getLogger(HttpClientBuilder.class);

 public boolean isSingleton() {
         return true;
     }

 @Override
 public Class<?> getObjectType() {
         return HttpClient.class;
     }

 @Override
 public HttpClient getObject() throws Exception {
 SSLContext sslContext = null;
   try {
          sslContext = mySSLSocketFactoryBean.getSSLContext();
   SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
   CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
   LOGGER.debug("HTTP BEAN");
   return httpClient;
  } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException
    | IOException e) {
   LOGGER.error("HTTPCLIENT BEAN CREATION FAILED");
   LOGGER.error("ERROR LOGGING");
   throw new CUSTOM_EXCEPTION(" SSL Failure");
  }

 }

 

No comments:

Post a Comment

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...