How to configure a Reactive WebClient to use 2-way TLS?











up vote
0
down vote

favorite












I'm trying to configure a reactive WebClient to use 2-way TLS. I used this answer as a reference. (The one using a WebClientCustomizer, not the one using an InsecureTrustManager).



I double-checked the keystores and truststores on both client and server side, but the server sends back an error saying that the client is not presenting any certificate:



  @Bean
WebClientCustomizer configureWebclient(@Value("${server.ssl.trust-store}") String trustStorePath, @Value("${server.ssl.trust-store-password}") String trustStorePass,
@Value("${server.ssl.key-store}") String keyStorePath, @Value("${server.ssl.key-store-password}") String keyStorePass, @Value("${server.ssl.key-alias}") String keyAlias) {

return new WebClientCustomizer() {

@Override
public void customize(Builder webClientBuilder) {
SslContext sslContext;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

List<Certificate> certificateCollcetion = Collections.list(trustStore.aliases()).stream().filter(t -> {
try {
return trustStore.isCertificateEntry(t);
} catch (KeyStoreException e1) {
throw new RuntimeException("Error reading truststore", e1);
}
}).map(t -> {
try {
return trustStore.getCertificate(t);
} catch (KeyStoreException e2) {
throw new RuntimeException("Error reading truststore", e2);
}
}).collect(Collectors.toList());

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());
sslContext = SslContextBuilder.forClient()
.keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
.trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
.build();
} catch (Exception e) {
log.error("Error creating web client", e);
throw new RuntimeException(e);
}
ClientHttpConnector connector = new ReactorClientHttpConnector((opt) -> {
opt.sslContext(sslContext);
});
webClientBuilder.clientConnector(connector);
}
};
}


Can somebody please share insight on how to correctly configure a reactive WebClient to use 2-way TLS?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm trying to configure a reactive WebClient to use 2-way TLS. I used this answer as a reference. (The one using a WebClientCustomizer, not the one using an InsecureTrustManager).



    I double-checked the keystores and truststores on both client and server side, but the server sends back an error saying that the client is not presenting any certificate:



      @Bean
    WebClientCustomizer configureWebclient(@Value("${server.ssl.trust-store}") String trustStorePath, @Value("${server.ssl.trust-store-password}") String trustStorePass,
    @Value("${server.ssl.key-store}") String keyStorePath, @Value("${server.ssl.key-store-password}") String keyStorePass, @Value("${server.ssl.key-alias}") String keyAlias) {

    return new WebClientCustomizer() {

    @Override
    public void customize(Builder webClientBuilder) {
    SslContext sslContext;
    try {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

    List<Certificate> certificateCollcetion = Collections.list(trustStore.aliases()).stream().filter(t -> {
    try {
    return trustStore.isCertificateEntry(t);
    } catch (KeyStoreException e1) {
    throw new RuntimeException("Error reading truststore", e1);
    }
    }).map(t -> {
    try {
    return trustStore.getCertificate(t);
    } catch (KeyStoreException e2) {
    throw new RuntimeException("Error reading truststore", e2);
    }
    }).collect(Collectors.toList());

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());
    sslContext = SslContextBuilder.forClient()
    .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
    .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
    .build();
    } catch (Exception e) {
    log.error("Error creating web client", e);
    throw new RuntimeException(e);
    }
    ClientHttpConnector connector = new ReactorClientHttpConnector((opt) -> {
    opt.sslContext(sslContext);
    });
    webClientBuilder.clientConnector(connector);
    }
    };
    }


    Can somebody please share insight on how to correctly configure a reactive WebClient to use 2-way TLS?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to configure a reactive WebClient to use 2-way TLS. I used this answer as a reference. (The one using a WebClientCustomizer, not the one using an InsecureTrustManager).



      I double-checked the keystores and truststores on both client and server side, but the server sends back an error saying that the client is not presenting any certificate:



        @Bean
      WebClientCustomizer configureWebclient(@Value("${server.ssl.trust-store}") String trustStorePath, @Value("${server.ssl.trust-store-password}") String trustStorePass,
      @Value("${server.ssl.key-store}") String keyStorePath, @Value("${server.ssl.key-store-password}") String keyStorePass, @Value("${server.ssl.key-alias}") String keyAlias) {

      return new WebClientCustomizer() {

      @Override
      public void customize(Builder webClientBuilder) {
      SslContext sslContext;
      try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

      List<Certificate> certificateCollcetion = Collections.list(trustStore.aliases()).stream().filter(t -> {
      try {
      return trustStore.isCertificateEntry(t);
      } catch (KeyStoreException e1) {
      throw new RuntimeException("Error reading truststore", e1);
      }
      }).map(t -> {
      try {
      return trustStore.getCertificate(t);
      } catch (KeyStoreException e2) {
      throw new RuntimeException("Error reading truststore", e2);
      }
      }).collect(Collectors.toList());

      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());
      sslContext = SslContextBuilder.forClient()
      .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
      .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
      .build();
      } catch (Exception e) {
      log.error("Error creating web client", e);
      throw new RuntimeException(e);
      }
      ClientHttpConnector connector = new ReactorClientHttpConnector((opt) -> {
      opt.sslContext(sslContext);
      });
      webClientBuilder.clientConnector(connector);
      }
      };
      }


      Can somebody please share insight on how to correctly configure a reactive WebClient to use 2-way TLS?










      share|improve this question













      I'm trying to configure a reactive WebClient to use 2-way TLS. I used this answer as a reference. (The one using a WebClientCustomizer, not the one using an InsecureTrustManager).



      I double-checked the keystores and truststores on both client and server side, but the server sends back an error saying that the client is not presenting any certificate:



        @Bean
      WebClientCustomizer configureWebclient(@Value("${server.ssl.trust-store}") String trustStorePath, @Value("${server.ssl.trust-store-password}") String trustStorePass,
      @Value("${server.ssl.key-store}") String keyStorePath, @Value("${server.ssl.key-store-password}") String keyStorePass, @Value("${server.ssl.key-alias}") String keyAlias) {

      return new WebClientCustomizer() {

      @Override
      public void customize(Builder webClientBuilder) {
      SslContext sslContext;
      try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

      List<Certificate> certificateCollcetion = Collections.list(trustStore.aliases()).stream().filter(t -> {
      try {
      return trustStore.isCertificateEntry(t);
      } catch (KeyStoreException e1) {
      throw new RuntimeException("Error reading truststore", e1);
      }
      }).map(t -> {
      try {
      return trustStore.getCertificate(t);
      } catch (KeyStoreException e2) {
      throw new RuntimeException("Error reading truststore", e2);
      }
      }).collect(Collectors.toList());

      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());
      sslContext = SslContextBuilder.forClient()
      .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
      .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
      .build();
      } catch (Exception e) {
      log.error("Error creating web client", e);
      throw new RuntimeException(e);
      }
      ClientHttpConnector connector = new ReactorClientHttpConnector((opt) -> {
      opt.sslContext(sslContext);
      });
      webClientBuilder.clientConnector(connector);
      }
      };
      }


      Can somebody please share insight on how to correctly configure a reactive WebClient to use 2-way TLS?







      java spring ssl reactive-programming






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 at 16:11









      DayTripperID

      93212




      93212
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          For some reason the server would not accept the client certificate when the ssl context was built like this:



          sslContext = SslContextBuilder.forClient()
          .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
          .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
          .build();


          To fix this, I had to initialize a KeyManagerFactory:



          KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
          keyManagerFactory.init(keyStore, keyStorePass.toCharArray());


          Then I initialized the ssl context with the factory:



          SslContext sslContext = SslContextBuilder.forClient()
          .keyManager(keyManagerFactory)
          .trustManager((X509Certificate) certificateCollection.toArray(new X509Certificate[certificateCollection.size()]))
          .build();


          After that, the server accepted the certificate and I could connect.



          In summary, I used this cleaner solution that utilizes factories for both the key-store and the trust-store:



          @Value("${server.ssl.trust-store}")
          String trustStorePath;
          @Value("${server.ssl.trust-store-password}")
          String trustStorePass;
          @Value("${server.ssl.key-store}")
          String keyStorePath;
          @Value("${server.ssl.key-store-password}")
          String keyStorePass;

          @Bean
          public WebClient create2WayTLSWebClient() {

          ClientHttpConnector connector = new ReactorClientHttpConnector(
          options -> {
          options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
          options.sslContext(get2WaySSLContext());
          }
          );

          return WebClient.builder()
          .clientConnector(connector)
          .build();

          }

          private SslContext get2WaySSLContext() {

          try {

          KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
          keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());

          KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
          keyManagerFactory.init(keyStore, keyStorePass.toCharArray());

          KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
          trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

          TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
          trustManagerFactory.init(trustStore);

          return SslContextBuilder.forClient()
          .keyManager(keyManagerFactory)
          .trustManager(trustManagerFactory)
          .build();

          } catch (Exception e) {
          logger.error("Error creating 2-Way TLS WebClient. Check key-store and trust-store.");
          e.printStackTrace();
          }

          return null;
          }


          Just a note, if you are using Spring 5.1 or newer, this specific implementation will not work as you can no longer pass HttpClientOptions to a ReactorClientHttpConnector. Use this link as a guide for that configuration. However the meat of the code in this answer should still be applicable to that sort of configuration.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341607%2fhow-to-configure-a-reactive-webclient-to-use-2-way-tls%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            For some reason the server would not accept the client certificate when the ssl context was built like this:



            sslContext = SslContextBuilder.forClient()
            .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
            .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
            .build();


            To fix this, I had to initialize a KeyManagerFactory:



            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            keyManagerFactory.init(keyStore, keyStorePass.toCharArray());


            Then I initialized the ssl context with the factory:



            SslContext sslContext = SslContextBuilder.forClient()
            .keyManager(keyManagerFactory)
            .trustManager((X509Certificate) certificateCollection.toArray(new X509Certificate[certificateCollection.size()]))
            .build();


            After that, the server accepted the certificate and I could connect.



            In summary, I used this cleaner solution that utilizes factories for both the key-store and the trust-store:



            @Value("${server.ssl.trust-store}")
            String trustStorePath;
            @Value("${server.ssl.trust-store-password}")
            String trustStorePass;
            @Value("${server.ssl.key-store}")
            String keyStorePath;
            @Value("${server.ssl.key-store-password}")
            String keyStorePass;

            @Bean
            public WebClient create2WayTLSWebClient() {

            ClientHttpConnector connector = new ReactorClientHttpConnector(
            options -> {
            options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            options.sslContext(get2WaySSLContext());
            }
            );

            return WebClient.builder()
            .clientConnector(connector)
            .build();

            }

            private SslContext get2WaySSLContext() {

            try {

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            keyManagerFactory.init(keyStore, keyStorePass.toCharArray());

            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            trustManagerFactory.init(trustStore);

            return SslContextBuilder.forClient()
            .keyManager(keyManagerFactory)
            .trustManager(trustManagerFactory)
            .build();

            } catch (Exception e) {
            logger.error("Error creating 2-Way TLS WebClient. Check key-store and trust-store.");
            e.printStackTrace();
            }

            return null;
            }


            Just a note, if you are using Spring 5.1 or newer, this specific implementation will not work as you can no longer pass HttpClientOptions to a ReactorClientHttpConnector. Use this link as a guide for that configuration. However the meat of the code in this answer should still be applicable to that sort of configuration.






            share|improve this answer



























              up vote
              0
              down vote



              accepted










              For some reason the server would not accept the client certificate when the ssl context was built like this:



              sslContext = SslContextBuilder.forClient()
              .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
              .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
              .build();


              To fix this, I had to initialize a KeyManagerFactory:



              KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
              keyManagerFactory.init(keyStore, keyStorePass.toCharArray());


              Then I initialized the ssl context with the factory:



              SslContext sslContext = SslContextBuilder.forClient()
              .keyManager(keyManagerFactory)
              .trustManager((X509Certificate) certificateCollection.toArray(new X509Certificate[certificateCollection.size()]))
              .build();


              After that, the server accepted the certificate and I could connect.



              In summary, I used this cleaner solution that utilizes factories for both the key-store and the trust-store:



              @Value("${server.ssl.trust-store}")
              String trustStorePath;
              @Value("${server.ssl.trust-store-password}")
              String trustStorePass;
              @Value("${server.ssl.key-store}")
              String keyStorePath;
              @Value("${server.ssl.key-store-password}")
              String keyStorePass;

              @Bean
              public WebClient create2WayTLSWebClient() {

              ClientHttpConnector connector = new ReactorClientHttpConnector(
              options -> {
              options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
              options.sslContext(get2WaySSLContext());
              }
              );

              return WebClient.builder()
              .clientConnector(connector)
              .build();

              }

              private SslContext get2WaySSLContext() {

              try {

              KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
              keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());

              KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
              keyManagerFactory.init(keyStore, keyStorePass.toCharArray());

              KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
              trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

              TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
              trustManagerFactory.init(trustStore);

              return SslContextBuilder.forClient()
              .keyManager(keyManagerFactory)
              .trustManager(trustManagerFactory)
              .build();

              } catch (Exception e) {
              logger.error("Error creating 2-Way TLS WebClient. Check key-store and trust-store.");
              e.printStackTrace();
              }

              return null;
              }


              Just a note, if you are using Spring 5.1 or newer, this specific implementation will not work as you can no longer pass HttpClientOptions to a ReactorClientHttpConnector. Use this link as a guide for that configuration. However the meat of the code in this answer should still be applicable to that sort of configuration.






              share|improve this answer

























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                For some reason the server would not accept the client certificate when the ssl context was built like this:



                sslContext = SslContextBuilder.forClient()
                .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
                .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
                .build();


                To fix this, I had to initialize a KeyManagerFactory:



                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
                keyManagerFactory.init(keyStore, keyStorePass.toCharArray());


                Then I initialized the ssl context with the factory:



                SslContext sslContext = SslContextBuilder.forClient()
                .keyManager(keyManagerFactory)
                .trustManager((X509Certificate) certificateCollection.toArray(new X509Certificate[certificateCollection.size()]))
                .build();


                After that, the server accepted the certificate and I could connect.



                In summary, I used this cleaner solution that utilizes factories for both the key-store and the trust-store:



                @Value("${server.ssl.trust-store}")
                String trustStorePath;
                @Value("${server.ssl.trust-store-password}")
                String trustStorePass;
                @Value("${server.ssl.key-store}")
                String keyStorePath;
                @Value("${server.ssl.key-store-password}")
                String keyStorePass;

                @Bean
                public WebClient create2WayTLSWebClient() {

                ClientHttpConnector connector = new ReactorClientHttpConnector(
                options -> {
                options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                options.sslContext(get2WaySSLContext());
                }
                );

                return WebClient.builder()
                .clientConnector(connector)
                .build();

                }

                private SslContext get2WaySSLContext() {

                try {

                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());

                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
                keyManagerFactory.init(keyStore, keyStorePass.toCharArray());

                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
                trustManagerFactory.init(trustStore);

                return SslContextBuilder.forClient()
                .keyManager(keyManagerFactory)
                .trustManager(trustManagerFactory)
                .build();

                } catch (Exception e) {
                logger.error("Error creating 2-Way TLS WebClient. Check key-store and trust-store.");
                e.printStackTrace();
                }

                return null;
                }


                Just a note, if you are using Spring 5.1 or newer, this specific implementation will not work as you can no longer pass HttpClientOptions to a ReactorClientHttpConnector. Use this link as a guide for that configuration. However the meat of the code in this answer should still be applicable to that sort of configuration.






                share|improve this answer














                For some reason the server would not accept the client certificate when the ssl context was built like this:



                sslContext = SslContextBuilder.forClient()
                .keyManager((PrivateKey) keyStore.getKey(keyAlias, keyStorePass.toCharArray()))
                .trustManager((X509Certificate) certificateCollcetion.toArray(new X509Certificate[certificateCollcetion.size()]))
                .build();


                To fix this, I had to initialize a KeyManagerFactory:



                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
                keyManagerFactory.init(keyStore, keyStorePass.toCharArray());


                Then I initialized the ssl context with the factory:



                SslContext sslContext = SslContextBuilder.forClient()
                .keyManager(keyManagerFactory)
                .trustManager((X509Certificate) certificateCollection.toArray(new X509Certificate[certificateCollection.size()]))
                .build();


                After that, the server accepted the certificate and I could connect.



                In summary, I used this cleaner solution that utilizes factories for both the key-store and the trust-store:



                @Value("${server.ssl.trust-store}")
                String trustStorePath;
                @Value("${server.ssl.trust-store-password}")
                String trustStorePass;
                @Value("${server.ssl.key-store}")
                String keyStorePath;
                @Value("${server.ssl.key-store-password}")
                String keyStorePass;

                @Bean
                public WebClient create2WayTLSWebClient() {

                ClientHttpConnector connector = new ReactorClientHttpConnector(
                options -> {
                options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                options.sslContext(get2WaySSLContext());
                }
                );

                return WebClient.builder()
                .clientConnector(connector)
                .build();

                }

                private SslContext get2WaySSLContext() {

                try {

                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(new FileInputStream(ResourceUtils.getFile(keyStorePath)), keyStorePass.toCharArray());

                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
                keyManagerFactory.init(keyStore, keyStorePass.toCharArray());

                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());

                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
                trustManagerFactory.init(trustStore);

                return SslContextBuilder.forClient()
                .keyManager(keyManagerFactory)
                .trustManager(trustManagerFactory)
                .build();

                } catch (Exception e) {
                logger.error("Error creating 2-Way TLS WebClient. Check key-store and trust-store.");
                e.printStackTrace();
                }

                return null;
                }


                Just a note, if you are using Spring 5.1 or newer, this specific implementation will not work as you can no longer pass HttpClientOptions to a ReactorClientHttpConnector. Use this link as a guide for that configuration. However the meat of the code in this answer should still be applicable to that sort of configuration.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 19 at 18:53

























                answered Nov 16 at 21:40









                DayTripperID

                93212




                93212






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341607%2fhow-to-configure-a-reactive-webclient-to-use-2-way-tls%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Costa Masnaga

                    Fotorealismo

                    Sidney Franklin