Reputation: 125
I need to setup an Apache HTTPAsyncClient with SSL support. I use this code, but it doesn't seem to work (getting "javax.net.ssl.SSLException: Received fatal alert: handshake_failure")
System.setProperty("javax.net.debug", "ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(loadStream("C:/TrustStore/cacerts"), "trustpass".toCharArray());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(loadStream("C:/KeyStore/SSL/keystore.SomeKey"), "keypass".toCharArray());
SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(ts).loadKeyMaterial(ks, "somekey".toCharArray()).setSecureRandom(new SecureRandom());
SSLContext ssl = sslBuilder.build();
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT));
CloseableHttpAsyncClient clientHttps = HttpAsyncClientBuilder.create()
.setConnectionManager(cm)
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLContext(ssl)
.build();
RequestConfig.Builder b = RequestConfig.custom();
b.setProxy(new HttpHost("proxyHost", proxyPort));
RequestConfig rc = b.build();
clientHttps.start();
HttpRequestBase req = new HttpPost("https://someurl");
((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity("somestring"));
req.setConfig(rc);
clientHttps.execute(req, new FutureCallback<HttpResponse>() {
@Override
public void failed(Exception ex) {
System.out.println(ex);
}
@Override
public void completed(HttpResponse result) {
System.out.println(result);
}
@Override
public void cancelled() {
System.out.println("Cancelled");
}
});
When using the javax.net.ssl.HttpsURLConnection to achive this, it works (I can attach the relevant code, if needed).
EDIT
Based on @ben75 answer, I finally make it running with the following code
System.setProperty("javax.net.debug", "ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(loadStream("C:/TrustStore/cacerts"), "trustpass".toCharArray());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(loadStream("C:/KeyStore/SSL/keystore.SomeKey"), "keypass".toCharArray());
SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(ts).loadKeyMaterial(ks, "somekey".toCharArray()).setSecureRandom(new SecureRandom());
SSLContext ssl = sslBuilder.build();
SSLIOSessionStrategy s = new SSLIOSessionStrategy(ssl, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
RegistryBuilder<SchemeIOSessionStrategy> rb = RegistryBuilder.create();
rb.register("https", s).register("http", NoopIOSessionStrategy.INSTANCE);
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), rb.build());
CloseableHttpAsyncClient clientHttps = HttpAsyncClientBuilder.create()
.setConnectionManager(cm)
.build();
RequestConfig.Builder b = RequestConfig.custom();
b.setProxy(new HttpHost("proxyHost", proxyPort));
RequestConfig rc = b.build();
clientHttps.start();
HttpRequestBase req = new HttpPost("https://someurl");
((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity("somestring"));
req.setConfig(rc);
clientHttps.execute(req, new FutureCallback<HttpResponse>() {
@Override
public void failed(Exception ex) {
System.out.println(ex);
}
@Override
public void completed(HttpResponse result) {
System.out.println(result);
}
@Override
public void cancelled() {
System.out.println("Cancelled");
}
});
Upvotes: 7
Views: 5832
Reputation: 65
There are a lot of great answers here but as of writing this answer, I found a lot of convenient builders in the httpcomponents library. For eg, in order to create a trust all based sslcontext, I used to following:
HttpAsyncClients.custom()
.setConnectionManager(PoolingAsyncClientConnectionManagerBuilder.create()
.setTlsStrategy(ClientTlsStrategyBuilder.create()
.setSslContext(SSLContextBuilder.create()
.loadTrustMaterial(null, new TrustAllStrategy())
.build())
.build())
.build())
.build()
Upvotes: 3
Reputation: 151
My example in asynchronous mode:
try {
SSLContext sslContext = getSSLContext(X509Cert);
CloseableHttpAsyncClient httpAsyncClient = getHttpAsyncClient(sslContext,HTTP_CLIENT_MAX_POOL_CONNECTIONS,HTTP_CLIENT_MAX_PER_ROUTE_CONN);
setHttpAsyncClient(httpAsyncClient);
} catch (Exception e) {
LOG.error("Generic SSL Error Adapter: {} - {}", e.getMessage(), e.getLocalizedMessage());
}
}
private SSLContext getSSLContext(X509CertificateValidator trustStrategy) {
try {
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, trustStrategy)
.build();
sslContext.getServerSessionContext().setSessionCacheSize(1000);
return sslContext;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
LOG.error("SSL Context creation error: {} - {}", e.getMessage(), e.getLocalizedMessage());
}
return null;
}
private Registry<SchemeIOSessionStrategy> getSSLRegistryAsync(SSLContext sslContext) {
Registry<SchemeIOSessionStrategy> defaultRegistry = RegistryBuilder.<SchemeIOSessionStrategy> create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
return defaultRegistry;
}
private PoolingNHttpClientConnectionManager getPoolingNHttpClientConnectionManager(SSLContext sslContext, int connectionPoolMax, int connectionPoolMaxPerRoute) {
try {
PoolingNHttpClientConnectionManager connectionManager =
new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), getSSLRegistryAsync(sslContext));
connectionManager.setMaxTotal(connectionPoolMax);
connectionManager.setDefaultMaxPerRoute(connectionPoolMaxPerRoute);
return connectionManager;
} catch (IOReactorException e) {
LOG.error("NHttp Connectio Manager error: {} - {}", e.getMessage(), e.getLocalizedMessage());
}
return null;
}
public CloseableHttpAsyncClient getHttpAsyncClient(SSLContext sslContext, int connectionPoolMax, int connectionPoolMaxPerRoute) {
final CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom()
.setConnectionManager(getPoolingNHttpClientConnectionManager(sslContext, connectionPoolMax, connectionPoolMaxPerRoute))
//.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
return httpAsyncClient;
}
Upvotes: 0
Reputation: 1054
Here is a working example:
public SSLContext getSSLContext() {
final TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
try {
final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
sslContext.getServerSessionContext().setSessionCacheSize(1000);
return sslContext;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
}
return null;
}
public Registry<SchemeIOSessionStrategy> getSSLRegistryAsync() {
return RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", new SSLIOSessionStrategy(
getSSLContext(), null, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)).build();
}
public PoolingNHttpClientConnectionManager getPoolingNHttpClientConnectionManager() {
try {
final PoolingNHttpClientConnectionManager connectionManager =
new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), getSSLRegistryAsync());
connectionManager.setMaxTotal(connectionPoolMax);
connectionManager.setDefaultMaxPerRoute(connectionPoolMaxPerRoute);
return connectionManager;
} catch (IOReactorException e) {
}
return null;
}
public RequestConfig getRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(socketTimeout)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.build();
}
public CloseableHttpAsyncClient getHttpAsyncClient() {
final CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom()
.setConnectionManager(getPoolingNHttpClientConnectionManager())
.setDefaultRequestConfig(getRequestConfig())
.build();
return httpAsyncClient;
}
Upvotes: 1
Reputation: 28706
(I run in very similar problem recently (on Android) but I guess you are making the same error as I did.)
When you set a connection manager explicitly : builder.setConnectionManager(cm)
the sslContext is ignored.
What you can do is inject your SSLContext in the PoolingNHttpClientConnectionManager.
To do so, you can use this constructor : PoolingNHttpClientConnectionManager(org.apache.http.nio.reactor.ConnectingIOReactor ioreactor, Registry iosessionFactoryRegistry)
with iosessionFactoryRegistry containing an SSLIOSessionStrategy build with your SSLContext
Upvotes: 5