下面列出了org.apache.http.impl.client.TargetAuthenticationStrategy#org.apache.http.conn.ssl.TrustStrategy 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 创建 SSL连接
*/
public static CloseableHttpClient createSSLInsecureClient() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() {
try {
SSLContext sslcontext = SSLContexts.custom()
//忽略掉对服务器端证书的校验
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
return new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
this.log.error(e.getMessage(), e);
}
return null;
}
/**
* custom http client for server with SSL errors
*
* @return
*/
public final CloseableHttpClient getCustomClient() {
try {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
(TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
builder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
builder.setConnectionManager(connMgr);
return builder.build();
} catch (Exception ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return getSystemClient();
}
CloseableHttpClient getHttpsClient()
{
try
{
RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build();
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true );
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE );
return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory )
.build();
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
}
return HttpClients.createDefault();
}
/**
* Creates {@link HttpClient} that trusts any SSL certificate
*
* @return prepared HTTP client
*/
protected HttpClient getSSLAcceptingClient() {
final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true;
try {
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build();
sslContext.init(null, getTrustManager(), new SecureRandom());
final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new NoopHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) {
ConsoleUtils.printError(error.getMessage());
throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error);
}
}
@Test
@RunAsClient
public void hello() throws IOException, GeneralSecurityException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
.build();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.build()) {
String response = Executor.newInstance(httpClient)
.execute(Request.Get("https://localhost:8443/"))
.returnContent().asString();
assertThat(response).contains("Hello on port 8443, secure: true");
}
}
@PostConstruct
protected void postConstruct() {
try {
if (uiConfig.isDisableHubApiTrustManager()) {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else {
httpClient = HttpClients.createSystem();
}
} catch (Exception e) {
logger.error("Error creating HTTP client.", e);
throw new RuntimeException(e);
}
}
public EsendexService(String user, String password, String account) {
this.user = user;
this.password = password;
this.account = account;
localContext = new BasicHttpContext();
httpClient = new DefaultHttpClient();
TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
};
SSLSocketFactory socketFactory = null;
try {
// socketFactory = new SSLSocketFactory(easyStrategy);
} catch (Exception exception){
logger.error(exception);
}
// Scheme sch = new Scheme("https", 443, socketFactory);
// httpClient.getConnectionManager().getSchemeRegistry().register(sch);
}
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException {
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(true).build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultSocketConfig(socketConfig);
httpClientBuilder.disableAuthCaching();
httpClientBuilder.disableAutomaticRetries();
if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) {
log.debug("Disabling all SSL certificate verification.");
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
httpClientBuilder.setSSLContext(sslContextBuilder.build());
}
return httpClientBuilder.build();
}
@Override
protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException {
final SSLContext sslContext;
try {
sslContext = SSLContextBuilder.create()
.loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
.build();
} catch (GeneralSecurityException e) {
throw new TTransportException("failed to initialize an SSL context", e);
}
final THttpClient client = new THttpClient(
uri, HttpClientBuilder.create()
.setSSLHostnameVerifier((hostname, session) -> true)
.setSSLContext(sslContext)
.build());
client.setCustomHeaders(
headers.names().stream()
.collect(toImmutableMap(AsciiString::toString,
name -> String.join(", ", headers.getAll(name)))));
return client;
}
private static CloseableHttpClient getHttpClient() throws
KeyManagementException, NoSuchAlgorithmException,
KeyStoreException {
// Relax SSL Certificate check
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
return true;
}
}).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE)).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(registry);
return HttpClients.custom().setConnectionManager(connectionManager)
.build();
}
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
final TrustStrategy acceptTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SchemeRegistry registry = new SchemeRegistry();
try {
final SSLSocketFactory ssf =
new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf));
} catch (Exception e) {
throw new ODataRuntimeException(e);
}
final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry));
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
return httpClient;
}
public static CloseableHttpClient createHttpClientTrustAll()
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setSSLSocketFactory(sslContextFactory)
.setRedirectStrategy(new LaxRedirectStrategy()).build();
return httpclient;
}
public HttpClient getHttpsClientTrustAll() {
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new AllowAllHostnameVerifier());
PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, psf));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception ex) {
log.error("Failed to create TrustAll https client", ex);
return new DefaultHttpClient();
}
}
public static HttpClient createHttpClientTrustAll(Optional<ProxyConfiguration> proxyConfiguration) throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//No operation verifier for trust All Client
HostnameVerifier allowAllHosts = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
public final String toString() {
return "NO_OP";
}
};
SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
return createClient(sslContextFactory, proxyConfiguration);
}
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(clientConnectionManager)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
/**
* Creates an HTTP client that trusts all upstream servers and uses a localhost proxy on the specified port.
*/
private static CloseableHttpClient getNewHttpClient(int proxyPort) {
try {
// Trust all certs -- under no circumstances should this ever be used outside of testing
SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
})
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setProxy(new HttpHost("127.0.0.1", proxyPort))
// disable decompressing content, since some tests want uncompressed content for testing purposes
.disableContentCompression()
.disableAutomaticRetries()
.build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException("Unable to create new HTTP client", e);
}
}
/**
* 执行http请求
*
* @param getMethod
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry registry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslsf)
.build();
HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setMaxConnPerRoute(50)
.setMaxConnTotal(100)
.setConnectionManager(httpClientConnectionManager)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
getMethod.setConfig(requestConfig);
HttpResponse response = httpClient.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
String result = EntityUtils.toString(response.getEntity());
throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
}
return response;
}
private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
{
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return factory;
}
public static CloseableHttpClient getNotValidatingClient(int timeout, String proxyServer, Integer proxyPort,
String proxyUser, String proxyPassword) {
try {
HttpClientBuilder clientBuilder = HttpClients.custom();
RequestConfig.Builder requestBuilder = RequestConfig.custom().setConnectTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000)
.setRedirectsEnabled(true);
if (StringUtils.isNotEmpty(proxyServer)) {
HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
requestBuilder.setProxy(proxyHost);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
clientBuilder.setRoutePlanner(routePlanner);
if (StringUtils.isNotEmpty(proxyUser)) {
CredentialsProvider credentialProvider = new BasicCredentialsProvider();
credentialProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUser, proxyPassword));
clientBuilder.setRoutePlanner(routePlanner);
}
}
RequestConfig requestConfig = requestBuilder.build();
CloseableHttpClient httpclient = clientBuilder.setHostnameVerifier(new AllowAllHostnameVerifier())
.setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).setDefaultRequestConfig(requestConfig).build();
return httpclient;
} catch (Throwable t) {
return null;
}
}
/**
* Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
* HEC.
*
* @param maxConnections max number of parallel connections.
* @param disableCertificateValidation should disable certificate validation.
*/
private CloseableHttpClient getHttpClient(
int maxConnections, boolean disableCertificateValidation)
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();
if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
LOG.info("SSL connection requested");
HostnameVerifier hostnameVerifier =
disableCertificateValidation
? NoopHostnameVerifier.INSTANCE
: new DefaultHostnameVerifier();
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
if (disableCertificateValidation) {
LOG.info("Certificate validation is disabled");
sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
}
SSLConnectionSocketFactory connectionSocketFactory =
new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
builder.setSSLSocketFactory(connectionSocketFactory);
}
builder.setMaxConnTotal(maxConnections);
builder.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
return builder.build();
}
public static CloseableHttpClient prepareClient()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(factory);
return builder.build();
}
@Override
protected Registry<ConnectionSocketFactory> getRegistry() {
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostName, SSLSession session) {
return true;
}
};
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
}
if (sslContext == null) {
throw new RuntimeException("SSL Context not created");
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1.2"}, null, verifier);
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
}
private boolean createClientDocker()
{
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpClientBuilder;
}
});
return createHighLevelClient(restClientBuilder);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
logger.error("Error while creating secure connection to ElasticSearch: ", e);
}
return false;
}
private boolean createClientDocker()
{
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpClientBuilder;
}
});
return createHighLevelClient(restClientBuilder);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
logger.error("Error while creating secure connection to ElasticSearch: ", e);
}
return false;
}
private static SSLContext createAcceptsAllCertsSSLContext()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
return (new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
return true;
}
}).build());
}
/**
* Creates a {@link CloseableHttpClient} to make HTTP POSTs against Splunk's HEC.
*
* @param maxConnections max number of parallel connections
* @param disableCertificateValidation should disable certificate validation
*/
private CloseableHttpClient getHttpClient(
int maxConnections, boolean disableCertificateValidation)
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();
if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
LOG.info("SSL connection requested");
HostnameVerifier hostnameVerifier =
disableCertificateValidation
? NoopHostnameVerifier.INSTANCE
: new DefaultHostnameVerifier();
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
if (disableCertificateValidation) {
LOG.info("Certificate validation is disabled");
sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
}
SSLConnectionSocketFactory connectionSocketFactory =
new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
builder.setSSLSocketFactory(connectionSocketFactory);
}
builder.setMaxConnTotal(maxConnections);
builder.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
return builder.build();
}
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
final RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
try {
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
sslContextBuilder.setProtocol(sslProtocol);
TrustStrategy trustStrategy = getTrustStrategy();
if (trustStrategy != null) {
LOG.debug("Set the TrustStrategy");
sslContextBuilder.loadTrustMaterial(null, trustStrategy);
}
final KeyStore sslTrustStore = getSSLTrustStore();
if (sslTrustStore != null) {
LOG.debug("Set the SSL trust store as trust materials");
sslContextBuilder.loadTrustMaterial(sslTrustStore, trustStrategy);
}
final KeyStore sslKeystore = getSSLKeyStore();
if (sslKeystore != null) {
LOG.debug("Set the SSL keystore as key materials");
final char[] password = sslKeystorePassword != null ? sslKeystorePassword.toCharArray() : null;
sslContextBuilder.loadKeyMaterial(sslKeystore, password);
if (loadKeyStoreAsTrustMaterial) {
LOG.debug("Set the SSL keystore as trust materials");
sslContextBuilder.loadTrustMaterial(sslKeystore, trustStrategy);
}
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), getSupportedSSLProtocols(),
getSupportedSSLCipherSuites(), getHostnameVerifier());
return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
} catch (final Exception e) {
throw new DSSException("Unable to configure the SSLContext/SSLConnectionSocketFactory", e);
}
}