2121
2222import javax .net .ssl .SSLContext ;
2323import javax .net .ssl .X509TrustManager ;
24+ import java .security .KeyManagementException ;
2425import java .security .NoSuchAlgorithmException ;
2526import java .util .LinkedHashMap ;
2627import java .util .Map ;
@@ -109,10 +110,12 @@ private DatabaseClientFactory.SecurityContext newSecurityContext() {
109110 }
110111 securityContext = newSecurityContext (type );
111112
112- SSLContext sslContext = determineSSLContext ();
113+ X509TrustManager trustManager = determineTrustManager ();
114+ SSLContext sslContext = determineSSLContext (trustManager );
113115 if (sslContext != null ) {
114- securityContext .withSSLContext (sslContext , determineTrustManager () );
116+ securityContext .withSSLContext (sslContext , trustManager );
115117 }
118+
116119 securityContext .withSSLHostnameVerifier (determineHostnameVerifier ());
117120 return securityContext ;
118121 }
@@ -180,10 +183,10 @@ private DatabaseClientFactory.SecurityContext newSAMLAuthContext() {
180183 );
181184 }
182185
183- private SSLContext determineSSLContext () {
184- Object sslContext = propertySource .apply (PREFIX + "sslContext" );
185- if (sslContext instanceof SSLContext ) {
186- return ( SSLContext ) sslContext ;
186+ private SSLContext determineSSLContext (X509TrustManager trustManager ) {
187+ SSLContext sslContext = ( SSLContext ) propertySource .apply (PREFIX + "sslContext" );
188+ if (sslContext != null ) {
189+ return sslContext ;
187190 }
188191 String protocol = (String ) propertySource .apply (PREFIX + "sslProtocol" );
189192 if (protocol != null ) {
@@ -195,13 +198,21 @@ private SSLContext determineSSLContext() {
195198 }
196199 }
197200 try {
198- // Note that if only a protocol is specified, and not a TrustManager, an attempt will later be made
199- // to use the JVM's default TrustManager
200- return SSLContext .getInstance (protocol );
201+ sslContext = SSLContext .getInstance (protocol );
201202 } catch (NoSuchAlgorithmException e ) {
202203 throw new RuntimeException ("Unable to get SSLContext instance with protocol: " + protocol
203204 + "; cause: " + e .getMessage (), e );
204205 }
206+ // Note that if only a protocol is specified, and not a TrustManager, an attempt will later be made
207+ // to use the JVM's default TrustManager
208+ if (trustManager != null ) {
209+ try {
210+ sslContext .init (null , new X509TrustManager []{trustManager }, null );
211+ } catch (KeyManagementException e ) {
212+ throw new RuntimeException ("Unable to initialize SSLContext; protocol: " + protocol + "; cause: " + e .getMessage (), e );
213+ }
214+ }
215+ return sslContext ;
205216 }
206217 return null ;
207218 }
0 commit comments