下面列出了怎么用org.apache.http.conn.ssl.TrustSelfSignedStrategy的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void setup() throws Exception {
this.server.setHandler(new CheckRequestHandler());
this.server.afterPropertiesSet();
this.server.start();
// Set dynamically chosen port
this.port = this.server.getPort();
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
builder.build(), NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpclient);
this.restTemplate = new RestTemplate(requestFactory);
}
@Before
public void setup() throws Exception {
this.server.setHandler(new CheckRequestHandler());
this.server.afterPropertiesSet();
this.server.start();
// Set dynamically chosen port
this.port = this.server.getPort();
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
builder.build(), NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpclient);
this.restTemplate = new RestTemplate(requestFactory);
}
public static void initPool() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
Dict.HTTPS, sslsf).build();
poolConnManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
poolConnManager.setMaxTotal(500);
poolConnManager.setDefaultMaxPerRoute(200);
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
httpClient = getConnection();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
logger.error("init http client pool failed:", ex);
}
}
public static HttpResponse httpGenericMethod(String url) {
HttpResponse response = null;
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf).build();
HttpGet httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
} catch (Exception e) {
LOGGER.error("Error occured while http GET" , e);
}
return response;
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
if (StringUtils.isNotBlank(service.getKeyStoreFile())){
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.useProtocol(service.getSslAlgorithm());
return sslContextBuilder.build();
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
SSLContextBuilder builder = SSLContexts.custom();
final String trustFilename = service.getTrustStoreFile();
if (trustFilename != null) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
final String keyFilename = service.getKeyStoreFile();
if (keyFilename != null) {
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
builder = builder.useProtocol(service.getSslAlgorithm());
final SSLContext sslContext = builder.build();
return sslContext;
}
public static PoolingHttpClientConnectionManager getConnctionManager(){
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
try {
SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
new TrustAllHostNameVerifier());
socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", trustSelfSignedSocketFactory)
.build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
Data.logger.warn("", e);
}
PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ?
new PoolingHttpClientConnectionManager(socketFactoryRegistry):
new PoolingHttpClientConnectionManager();
// twitter specific options
cm.setMaxTotal(2000);
cm.setDefaultMaxPerRoute(200);
return cm;
}
private SSLContext getSSLContext(KeyStore keyStore, String keyStoreValue, KeyStore trustStore) {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStoreValue.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
sslContext.init(keyManagers, trustManagers, new SecureRandom());
return sslContext;
} catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
/**
* 创建httpclient连接池,并初始化httpclient
*/
public void init() {
try {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
new TrustSelfSignedStrategy())
.build();
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf)
.build();
httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
httpClientConnectionManager.setMaxTotal(maxTotalPool);
// Increase default max connection per route to 20
httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
} catch (Exception e) {
}
}
private static CloseableHttpClient makeHttpClient(boolean verify) {
CloseableHttpClient httpclient = null;
if (verify) {
httpclient = HttpClients.createDefault();
} else {
//SSLContextBuilder builder;
//SSLConnectionSocketFactory sslsf=null;
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
System.out.println(e);
}
}
return (httpclient);
}
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
final char[] pwd = password.toCharArray();
SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
.loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
;
if (keystoreFile != null) {
sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
}
sslcontextBuilder.setProtocol("TLSv1.2");
return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
@Override
public boolean verify(final String s, final SSLSession sslSession) {
return true;
}
});
}
public static CloseableHttpClient buildHttpClient(AviCredentials creds) {
CloseableHttpClient httpClient = null;
if (!creds.getVerify()) {
SSLContext sslcontext = null;
try {
sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (Exception e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,
(s, sslSession) -> true);
httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
.setSSLSocketFactory(sslConnectionSocketFactory)
.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
.build();
} else {
httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
.build();
}
return httpClient;
}
public static WireMockConfiguration options() {
if (!initialized) {
if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier",
null)) {
HttpsURLConnection
.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
try {
HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
.loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
.build().getSocketFactory());
}
catch (Exception e) {
throw new AssertionError("Cannot install custom socket factory: ["
+ e.getMessage() + "]");
}
}
initialized = true;
}
return new WireMockConfiguration();
}
public CustomHttpClient(String url, String user, String pass) throws Exception {
this.openviduUrl = url.replaceFirst("/*$", "");
this.headerAuth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes());
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new Exception("Error building custom HttpClient: " + e.getMessage());
}
HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
Unirest.setHttpClient(unsafeHttpClient);
}
public AbstractRestTemplateClient ignoreAuthenticateServer() {
//backward compatible with android httpclient 4.3.x
if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer");
}
return this;
}
/**
* This method creates an insecure SSL factory that will trust on self signed certificates.
* For that we use {@link TrustSelfSignedStrategy}.
*/
protected SSLConnectionSocketFactory createInsecureSslFactory() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustSelfSignedStrategy());
SSLContext sc = builder.build();
if (acceptAllKindsOfCertificates) {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new TrustAllManager();
trustAllCerts[0] = tm;
sc.init(null, trustAllCerts, null);
HostnameVerifier hostnameVerifier = createInsecureHostNameVerifier();
return new SSLConnectionSocketFactory(sc, hostnameVerifier);
}
return new SSLConnectionSocketFactory(sc);
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new ApacheCloudStackClientRuntimeException(e);
}
}
private void createNewConnectionManager() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build(), NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf)
.build();
connectionManager = new PoolingHttpClientConnectionManager(r);
connectionManager.setValidateAfterInactivity(500);
sharedContext = ThreadLocal.withInitial(HttpClientContext::new);
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected void init() throws GerbilException {
HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
try {
keyStore.load(instream, KEY_STORE_PASSWORD);
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
.build();
builder.setSSLContext(sslcontext);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
builder.setSSLSocketFactory(sslsf);
CloseableHttpClient localClient = builder.build();
this.setClient(localClient);
} catch (Exception e) {
throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
}
this.setClient(builder.build());
}
private void httpConfig() {
LOG.info("Setting up http Matrix Federation for id: " + userId);
SSLContext sslcontext;
try {
sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLContext(sslcontext)
.build();
Unirest.setHttpClient(httpclient);
Unirest.setDefaultHeader("Content-Type","application/json");
}
@Bean
public CloseableHttpClient httpClient() {
try {
//new ClassPathResource("").getURL()
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(keyStore, keyPassword.toCharArray(),
new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslcontext, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
} catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new BeanCreationException("Failed to create http client for ssl connection", e);
}
}
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host, 25555),
new UsernamePasswordCredentials(username, password));
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.useTLS()
.build();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
HttpClient httpClient = HttpClientBuilder.create()
.disableRedirectHandling()
.setDefaultCredentialsProvider(credentialsProvider)
.setSSLSocketFactory(connectionFactory)
.build();
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
restTemplate.getInterceptors().addAll(interceptors);
return restTemplate;
}
@Test
public void testHttpsDoesNotReturnJettyServerVersionHeader() throws Exception {
final HttpGet httpget = new HttpGet(httpsUri + "/test/endpoint");
// trust all self-signed certs and add the client keystore if it's configured.
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.loadKeyMaterial(new File(clientKeystoreLocation),SSL_PASSWORD.toCharArray(),
SSL_PASSWORD.toCharArray())
.build();
final SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
try ( CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslSf).build();
CloseableHttpResponse response = httpclient.execute(httpget) ) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getFirstHeader( "Server" ), is(nullValue()));
}
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
if (StringUtils.isNotBlank(service.getKeyStoreFile())) {
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.useProtocol(service.getSslAlgorithm());
return sslContextBuilder.build();
}
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
// new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
final char[] pwd = password.toCharArray();
SSLContextBuilder sslcontextBuilder = SSLContexts.custom()//
.loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)//
;
if (keystoreFile != null) {
sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
}
return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
@Override
public boolean verify(final String s, final SSLSession sslSession) {
return true;
}
});
}
public static void setSkipCertificateValidation() {
if (!tlsWarningEmitted.getAndSet(true)) {
// Since this is a static util, it may happen that TLS is setup many times in one command
// invocation (e.g. when a command requires logging in). However, we would like to
// prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
System.err.println("The server is configured to use TLS but there is no truststore specified.");
System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
}
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
sslsf = new SSLConnectionSocketFactory(builder.build());
} catch (Exception e) {
throw new RuntimeException("Failed setting up TLS", e);
}
}
public static void setSkipCertificateValidation() {
if (!tlsWarningEmitted.getAndSet(true)) {
// Since this is a static util, it may happen that TLS is setup many times in one command
// invocation (e.g. when a command requires logging in). However, we would like to
// prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
System.err.println("The server is configured to use TLS but there is no truststore specified.");
System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
}
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
sslsf = new SSLConnectionSocketFactory(builder.build());
} catch (Exception e) {
throw new RuntimeException("Failed setting up TLS", e);
}
}
@Bean
public CloseableHttpClient httpClient() throws Exception {
if (tlsEnabled) {
Resource resource = new FileSystemResource(tlsKeystore);
File trustStoreFile = resource.getFile();
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(trustStoreFile, tlsKeystorePassword.toCharArray(),
new TrustSelfSignedStrategy())
.build();
HostnameVerifier hostnameVerifier = (s, sslSession) -> {
// Custom logic to verify host name, tlsHostnameVerifier is false for test
if (!tlsHostnameVerifier) {
return true;
} else {
HostnameVerifier hv= HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify(s, sslSession);
}
};
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
hostnameVerifier);
return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
}
return HttpClients.custom().build();
}
private javax.net.ssl.SSLContext buildSslContext() {
try {
return new SSLContextBuilder().useSSL()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
} catch (GeneralSecurityException gse) {
throw new RuntimeException("An error occurred setting up the SSLContext", gse);
}
}
private CloseableHttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
new AllowAllHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
}