Skip to content

RestTemplateBuilder custom request factory, cannot pass client and keep default sslbundle configuration #36594

Open
@krodyrobi

Description

@krodyrobi

By default ClientHttpRequestFactories created using RestTemplateBuilder.requestFactory(settings) will have only 3 properties applicable sslbundle and some timeouts.

If I need to have both ssl and for instance configure some more flags on the specific client I cannot use the factory, and I am forced to either duplicate the FactoryLogic (client is not protected so extending does not help) or duplicate the property / ssl configuration.

builder
   .setSslBundle(bundles.getBundle("some"))
   .requestFactory((settings) -> {
       // no way to pass client here
       return ClientHttpRequestFactories.get(OkHttp3ClientHttpRequestFactory.class, settings);
    })
    .build()
builder
    .setSslBundle(bundles.getBundle("some"))
   .requestFactory((settings) -> {
       var clientBuilder = new OkHttpClient.Builder();
       clientBuilder.callTimeout(Duration.ofSeconds(3));

       // Adapted from ClientHttpRequestFactories.OkHttp
       Assert.state(settings.bufferRequestBody() == null, 
            () -> "OkHttp3ClientHttpRequestFactory does not support request body buffering");
       PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
       map.from(settings::connectTimeout).to(clientBuilder::connectTimeout);
       map.from(settings::readTimeout).to(clientBuilder::readTimeout);

       SslBundle sslBundle = settings.sslBundle();
       if (sslBundle != null) {
           Assert.state(!sslBundle.getOptions().isSpecified(), "SSL Options cannot be specified with OkHttp");
           SSLSocketFactory socketFactory = sslBundle.createSslContext().getSocketFactory();
           TrustManager[] trustManagers = sslBundle.getManagers().getTrustManagers();
            Assert.state(trustManagers.length == 1,
               "Trust material must be provided in the SSL bundle for OkHttp3ClientHttpRequestFactory");
            clientBuilder
                .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0]);

       }
       return new OkHttp3ClientHttpRequestFactory(clientBuilder.build());
  })
  .build();

Metadata

Metadata

Assignees

No one assigned

    Labels

    theme: http-client-configIssues related to configuration of HTTP clientstheme: sslIssues related to ssl supporttype: bugA general bug

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions