List of usage examples for org.apache.http.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java
private CloseableHttpClient buildHttpClient() { KeyStore keyStore = null;// w w w. j av a 2s . c om KeyStore trustStore = null; FileInputStream instreamKeystore = null; FileInputStream instreamTruststore = null; try { keyStore = KeyStore.getInstance("jks"); instreamKeystore = new FileInputStream(keystorePath); keyStore.load(instreamKeystore, keystorePassword.toCharArray()); if (truststorePath != null && !truststorePath.isEmpty()) { trustStore = KeyStore.getInstance("jks"); instreamTruststore = new FileInputStream(truststorePath); trustStore.load(instreamTruststore, truststorePassword.toCharArray()); } } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (CertificateException e) { log.error("Threw exception", e); return null; } catch (IOException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } finally { try { if (instreamKeystore != null) { instreamKeystore.close(); } if (instreamTruststore != null) { instreamTruststore.close(); } } catch (IOException e) { log.error("Threw exception", e); } } // Trust own CA and all self-signed certs SSLContext sslcontext; try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); // If you have a trust store - should only be needed when the site we contact use self-signed certificates. if (trustStore != null) { sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); } sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray()); sslcontext = sslContextBuilder.build(); } catch (KeyManagementException e) { log.error("Threw exception", e); return null; } catch (UnrecoverableKeyException e) { log.error("Threw exception", e); return null; } catch (NoSuchAlgorithmException e) { log.error("Threw exception", e); return null; } catch (KeyStoreException e) { log.error("Threw exception", e); return null; } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }
From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptor.java
/** * Calls a resource in CDR with redirect disabled. Then it is possible to catch if the user is redirected to login page. * * @param url CDR url to fetch.//from ww w. j a v a2 s . c om * @param headers HTTP headers to send. * @return HTTP response object * @throws IOException if network error occurs * @throws java.security.NoSuchAlgorithmException * @throws java.security.KeyManagementException */ protected CloseableHttpResponse fetchUrlWithoutRedirection(String url, HttpHeaders headers) throws IOException, NoSuchAlgorithmException, KeyManagementException { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLContext(SSLContexts.custom().useProtocol("TLSv1.2").build()) .setRedirectStrategy(new RedirectStrategy() { @Override public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException { return false; } @Override public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException { return null; } }); HttpGet httpget = new HttpGet(url); for (Map.Entry<String, List<String>> header : headers.entrySet()) { for (String value : header.getValue()) { httpget.addHeader(header.getKey(), value); } } CloseableHttpClient client = httpClientBuilder.build(); CloseableHttpResponse httpResponse = client.execute(httpget); return httpResponse; }
From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java
public static void setTruststore(File file, String password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { if (!file.isFile()) { throw new RuntimeException("Truststore file not found: " + file.getAbsolutePath()); }//from ww w . j av a 2 s. c o m SSLContext theContext = SSLContexts.custom().useProtocol("TLS") .loadTrustMaterial(file, password == null ? null : password.toCharArray()).build(); sslsf = new SSLConnectionSocketFactory(theContext); }
From source file:org.elasticsearch.test.rest.client.RestTestClient.java
private static RestClient createRestClient(URL[] urls, Settings settings) throws IOException { String protocol = settings.get(PROTOCOL, "http"); HttpHost[] hosts = new HttpHost[urls.length]; for (int i = 0; i < hosts.length; i++) { URL url = urls[i];//from ww w .j av a2 s. c o m hosts[i] = new HttpHost(url.getHost(), url.getPort(), protocol); } RestClient.Builder builder = RestClient.builder(hosts).setMaxRetryTimeoutMillis(30000) .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(30000)); String keystorePath = settings.get(TRUSTSTORE_PATH); if (keystorePath != null) { final String keystorePass = settings.get(TRUSTSTORE_PASSWORD); if (keystorePass == null) { throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD); } Path path = PathUtils.get(keystorePath); if (!Files.exists(path)) { throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file"); } try { KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream is = Files.newInputStream(path)) { keyStore.load(is, keystorePass.toCharArray()); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext); builder.setHttpClientConfigCallback( new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory)); } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) { throw new RuntimeException(e); } } try (ThreadContext threadContext = new ThreadContext(settings)) { Header[] defaultHeaders = new Header[threadContext.getHeaders().size()]; int i = 0; for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) { defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue()); } builder.setDefaultHeaders(defaultHeaders); } return builder.build(); }
From source file:com.liferay.sync.engine.session.Session.java
private static SSLConnectionSocketFactory _getTrustingSSLSocketFactory() throws Exception { if (_trustingSSLSocketFactory == null) { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(new TrustStrategy() { @Override/*w w w . jav a 2 s.co m*/ public boolean isTrusted(X509Certificate[] x509Certificates, String authType) { return true; } }); _trustingSSLSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), new NoopHostnameVerifier()); } return _trustingSSLSocketFactory; }
From source file:org.commonjava.util.jhttpc.HttpFactory.java
private SSLConnectionSocketFactory createSSLSocketFactory(final SiteConfig location) throws JHttpCException { SSLConnectionSocketFactory fac = (SSLConnectionSocketFactory) location.getAttribute(SSL_FACTORY_ATTRIB); if (fac != null) { return fac; }//ww w . ja va2 s . co m KeyStore ks = null; KeyStore ts = null; final String kcPem = location.getKeyCertPem(); final String kcPass = passwords.lookup(new PasswordKey(location, PasswordType.KEY)); if (kcPem != null) { logger.debug("Adding client key/certificate from: {}", location); if (kcPass == null || kcPass.length() < 1) { logger.error("Invalid configuration. Location: {} cannot have an empty key password!", location.getUri()); throw new JHttpCException( "Location: " + location.getUri() + " is misconfigured! Key password cannot be empty."); } try { logger.trace("Reading Client SSL key from:\n\n{}\n\n", kcPem); ks = SSLUtils.readKeyAndCert(kcPem, kcPass); logger.trace("Keystore contains the following certificates: {}", new CertEnumerator(ks, kcPass)); } catch (final CertificateException e) { logger.error(String.format( "Invalid configuration. Location: %s has an invalid client certificate! Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final KeyStoreException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final InvalidKeySpecException e) { logger.error( String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (IOException e) { throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e, location, e.getMessage()); } catch (JHttpCException e) { throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e, location, e.getMessage()); } } else { logger.debug("No client key/certificate found"); } final String sPem = location.getServerCertPem(); // logger.debug( "Server certificate PEM:\n{}", sPem ); if (sPem != null) { logger.debug("Loading TrustStore (server SSL) information from: {}", location); try { logger.trace("Reading Server SSL cert from:\n\n{}\n\n", sPem); ts = SSLUtils.decodePEMTrustStore(sPem, location.getHost()); logger.trace("Trust store contains the following certificates:\n{}", new CertEnumerator(ts, null)); } catch (final CertificateException e) { logger.error(String.format( "Invalid configuration. Location: %s has an invalid server certificate! Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final KeyStoreException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", location.getUri(), e.getMessage()), e); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (IOException e) { throw new JHttpCException( "Failed to read server SSL certificate(s) (or couldn't parse server hostname) from: %s. Reason: %s", e, location, e.getMessage()); } } else { logger.debug("No server certificates found"); } if (ks != null || ts != null) { logger.debug("Setting up SSL context."); try { SSLContextBuilder sslBuilder = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS); if (ks != null) { logger.trace("Loading key material for SSL context..."); PrivateKeyStrategy pkStrategy = new MonolithicKeyStrategy(); sslBuilder.loadKeyMaterial(ks, kcPass.toCharArray(), pkStrategy); } if (ts != null) { logger.trace("Loading trust material for SSL context..."); SiteTrustType trustType = location.getTrustType(); if (trustType == null) { trustType = SiteTrustType.DEFAULT; } sslBuilder.loadTrustMaterial(ts, trustType.getTrustStrategy()); } SSLContext ctx = sslBuilder.build(); fac = new SSLConnectionSocketFactory(ctx, new DefaultHostnameVerifier()); location.setAttribute(SSL_FACTORY_ATTRIB, fac); return fac; } catch (final KeyManagementException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, location.getUri(), e.getMessage()); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final UnrecoverableKeyException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, location.getUri(), e.getMessage()); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, location.getUri(), e.getMessage()); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } catch (final KeyStoreException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, location.getUri(), e.getMessage()); throw new JHttpCException( "Failed to initialize SSL connection for repository: " + location.getUri()); } } else { logger.debug("No SSL configuration present; no SSL context created."); } return null; }
From source file:org.elasticsearch.client.documentation.RestClientDocumentation.java
@SuppressWarnings("unused") public void testCommonConfiguration() throws Exception { {//from ww w . j a v a2 s. c o m //tag::rest-client-config-timeouts RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200)) .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig( RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000); } }).setMaxRetryTimeoutMillis(60000); //end::rest-client-config-timeouts } { //tag::rest-client-config-threads RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultIOReactorConfig( IOReactorConfig.custom().setIoThreadCount(1).build()); } }); //end::rest-client-config-threads } { //tag::rest-client-config-basic-auth final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password")); RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); //end::rest-client-config-basic-auth } { //tag::rest-client-config-disable-preemptive-auth final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password")); RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { httpClientBuilder.disableAuthCaching(); // <1> return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); //end::rest-client-config-disable-preemptive-auth } { Path keyStorePath = Paths.get(""); String keyStorePass = ""; //tag::rest-client-config-encrypted-communication KeyStore truststore = KeyStore.getInstance("jks"); try (InputStream is = Files.newInputStream(keyStorePath)) { truststore.load(is, keyStorePass.toCharArray()); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null); final SSLContext sslContext = sslBuilder.build(); RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "https")) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setSSLContext(sslContext); } }); //end::rest-client-config-encrypted-communication } }