List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory
public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory)
From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java
/** * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds * * @param keyPair the keypair to generate the csr for * @throws IOException if there is a problem during the process * @return the resulting certificate chain *///from www .j a v a 2 s . c o m public X509Certificate[] perform(KeyPair keyPair) throws IOException { try { List<X509Certificate> certificates = new ArrayList<>(); HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.useProtocol("TLSv1.2"); // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory( sslContextBuilder.build(), caHostname, certificates)); String jsonResponseString; int responseCode; try (CloseableHttpClient client = httpClientBuilder.build()) { JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm); TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest( TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request)); HttpPost httpPost = new HttpPost(); httpPost.setEntity( new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest))); if (logger.isInfoEnabled()) { logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port); } try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) { jsonResponseString = IOUtils.toString( new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8); responseCode = response.getStatusLine().getStatusCode(); } } if (responseCode != Response.SC_OK) { throw new IOException( RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString); } if (certificates.size() != 1) { throw new IOException(EXPECTED_ONE_CERTIFICATE); } TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class); if (!tlsCertificateAuthorityResponse.hasHmac()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC); } X509Certificate caCertificate = certificates.get(0); byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey()); if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) { throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE); } if (!tlsCertificateAuthorityResponse.hasCertificate()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE); } X509Certificate x509Certificate = TlsHelper .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate())); x509Certificate.verify(caCertificate.getPublicKey()); if (logger.isInfoEnabled()) { logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal()); } return new X509Certificate[] { x509Certificate, caCertificate }; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
From source file:org.osgpfoundation.osgp.webdemoapp.infra.platform.SoapRequestHelper.java
/** * Creates a HttpComponentsMessageSender for communication with the * platform./*from ww w. j av a 2s . c o m*/ * * @return HttpComponentsMessageSender */ private HttpComponentsMessageSender createHttpMessageSender() { final HttpComponentsMessageSender sender = new HttpComponentsMessageSender(); final HttpClientBuilder builder = HttpClients.custom(); builder.addInterceptorFirst(new ContentLengthHeaderRemoveInterceptor()); try { final SSLContext sslContext = new SSLContextBuilder() .loadKeyMaterial(this.keyStoreHelper.getKeyStore(), this.keyStoreHelper.getKeyStorePwAsChar()) .loadTrustMaterial(this.keyStoreHelper.getTrustStore()).build(); final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext); builder.setSSLSocketFactory(sslConnectionFactory); sender.setHttpClient(builder.build()); } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) { e.printStackTrace(); } return sender; }
From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java
/** * It creates an {@link CloseableHttpClient} object. * If {@link #validateServerHttpsCertificate} indicates that we should not validate HTTPS server certificate, we use an insecure SSL factory; the insecure factory is created using {@link #createInsecureSslFactory()}. *//*from www . jav a 2 s . c om*/ protected CloseableHttpClient createHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (!validateServerHttpsCertificate) { SSLConnectionSocketFactory sslsf = createInsecureSslFactory(); httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:com.github.technosf.posterer.modules.commons.transport.CommonsRequestModelImpl.java
/** * Configures builder for the given SSL/TLS version * //from ww w . ja va2s .c om * @param builder * the builder to configure * @param ssl * the ssl info */ private @Nullable BooleanSupplier buildInSSL(Auditor auditor, HttpClientBuilder builder, final String ssl, final KeyStoreBean keyStoreBean, final String alias) { builder.setSSLHostnameVerifier(new PromiscuousHostnameVerifier(auditor)); try { AuditingSSLSocketFactory auditingSSLSocketFactory = new AuditingSSLSocketFactory(auditor, ssl, keyStoreBean, alias); builder.setSSLSocketFactory(auditingSSLSocketFactory); return auditingSSLSocketFactory.getNeededClientAuthSupplier(); } catch (KeyManagementException | UnrecoverableKeyException e) { auditor.append(true, CONST_ERR_SSL_KEY).append(false, "\t%1$s", e.getMessage()); } catch (NoSuchAlgorithmException e) { auditor.append(true, CONST_ERR_SSL_ALGO).append(false, "\t%1$s", e.getMessage()); } catch (KeyStoreException e) { auditor.append(true, CONST_ERR_SSL_STORE).append(false, "\t%1$s", e.getMessage()); } catch (FileNotFoundException e) { auditor.append(true, CONST_ERR_SSL_FILE).append(false, "\t%1$s", e.getMessage()); } catch (CertificateException e) { auditor.append(true, CONST_ERR_SSL_CERT).append(false, "\t%1$s", e.getMessage()); } catch (IOException e) { auditor.append(true, CONST_ERR_SSL_IO).append(false, "\t%1$s", e.getMessage()); } return null; }
From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java
private static HttpClient buildClient(URL proxy, String username, String password) throws Exception { HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client. // Create an Apache HttpClientBuilder to be customized by the command line arguments. HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties(); // Proxy//w w w . j ava 2 s.c om if (proxy != null) { HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol()); builder.setProxy(proxyHost); } // Basic authentication. User & Password if (username != null ^ password != null) { throw new Exception("'username' and 'password' arguments are required to appear together."); } // from: http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3 SSLContextBuilder ssbldr = new SSLContextBuilder(); ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(20);//max connection System.setProperty("jsse.enableSNIExtension", "false"); //"" CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build(); client.setHttpclient(httpClient); return client; }
From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImplIT.java
private void setSSL(HttpClientBuilder builder) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(this.getClass().getClassLoader().getResource("testkeystore"), "password".toCharArray(), new TrustSelfSignedStrategy()) .build();/*from www. ja v a 2 s .com*/ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare asynchronous connection./* w w w . j a v a 2 s.c om*/ * * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { //ssl config HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); builder.setSchemePortResolver(new DefaultSchemePortResolver()); EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger); builder.setSSLSocketFactory(factory); builder.setSslcontext(factory.getContext()); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); // builder.setDefaultRequestConfig(rcBuilder.build()); //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects //create the client and execute requests client = builder.build(); httpPostReq = new HttpPost(getUrl().toString()); response = client.execute(httpPostReq); } catch (IOException e) { client = null; httpPostReq = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } catch (Exception e) { client = null; httpPostReq = null; e.printStackTrace(); throw new EWSHttpException("SSL problem " + this.getUrl()); } }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {// w w w . jav a 2 s . c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { log.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpClient(Settings settings, HttpAuthRegistry httpAuthRegistry, SSLService sslService) { super(settings); this.httpAuthRegistry = httpAuthRegistry; this.defaultConnectionTimeout = HttpSettings.CONNECTION_TIMEOUT.get(settings); this.defaultReadTimeout = HttpSettings.READ_TIMEOUT.get(settings); this.maxResponseSize = HttpSettings.MAX_HTTP_RESPONSE_SIZE.get(settings); this.settingsProxy = getProxyFromSettings(); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); // ssl setup//from ww w .j av a2 s .com Settings sslSettings = settings.getByPrefix(SETTINGS_SSL_PREFIX); boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY) .isHostnameVerificationEnabled(); HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory( sslService.sslSocketFactory(sslSettings), verifier); clientBuilder.setSSLSocketFactory(factory); clientBuilder.evictExpiredConnections(); clientBuilder.setMaxConnPerRoute(MAX_CONNECTIONS); clientBuilder.setMaxConnTotal(MAX_CONNECTIONS); client = clientBuilder.build(); }
From source file:net.ymate.framework.commons.HttpClientHelper.java
private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException { HttpClientBuilder _builder = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout) .setSocketTimeout(__socketTimeout).setConnectionRequestTimeout(__requestTimeout).build()); if (__socketFactory == null) { __socketFactory = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(), NoopHostnameVerifier.INSTANCE); }//w ww . j a va 2 s . c o m return _builder.setSSLSocketFactory(__socketFactory).build(); }