List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointAuthority.java
protected void getSharePointSession() throws ManifoldCFException { if (proxy == null) { // Set up server URL try {//from w w w. ja v a2 s. c o m if (serverPortString == null || serverPortString.length() == 0) { if (serverProtocol.equals("https")) this.serverPort = 443; else this.serverPort = 80; } else this.serverPort = Integer.parseInt(serverPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } int proxyPort = 8080; if (proxyPortString != null && proxyPortString.length() > 0) { try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } } serverUrl = serverProtocol + "://" + serverName; if (serverProtocol.equals("https")) { if (serverPort != 443) serverUrl += ":" + Integer.toString(serverPort); } else { if (serverPort != 80) serverUrl += ":" + Integer.toString(serverPort); } fileBaseUrl = serverUrl + encodedServerLocation; int connectionTimeout = 60000; int socketTimeout = 900000; // Set up ssl if indicated connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); SSLConnectionSocketFactory myFactory = null; if (keystoreData != null) { keystoreManager = KeystoreManagerFactory.make("", keystoreData); myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), new BrowserCompatHostnameVerifier()); } if (strippedUserName != null) { credentialsProvider.setCredentials(new AuthScope(serverName, serverPort), new NTCredentials(strippedUserName, password, currentHost, ntlmDomain)); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider); if (myFactory != null) builder.setSSLSocketFactory(myFactory); builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); httpClient = builder.build(); proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, serverUserName, password, org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd", httpClient, isClaimSpace); } sharepointSessionTimeout = System.currentTimeMillis() + SharePointExpirationInterval; }
From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java
/** * Utility method to send a slo request to a participant via GET message. * @param requestUrl/*from w w w . j av a 2 s . c o m*/ * @throws URISyntaxException * @throws IOException * @throws ClientProtocolException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ static void sendSLORequestToOtherParticipant(String requestUrl) throws URISyntaxException, ClientProtocolException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { if (requestUrl == null || requestUrl.isEmpty()) return; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); URI httpUri = new URI(requestUrl); HttpGet httpGet = new HttpGet(httpUri); CloseableHttpResponse response = client.execute(httpGet); response.close(); }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java
private HttpClientBuilder ignoreCertificate() throws NoSuchAlgorithmException, KeyManagementException { System.setProperty("jsse.enableSNIExtension", "false"); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }//from w w w . j ava2 s.c o m public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; SSLContext sslContext; sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslsf).build(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); return HttpClients.custom().setConnectionManager(cm); }
From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java
private SSLConnectionSocketFactory createSSLConnectionSocketFactory() { SSLConnectionSocketFactory sf = null; for (String contextName : SSL_CONTEXT_NAMES) { try {/* w w w.j a v a2s . co m*/ SSLContext sslContext = SSLContext.getInstance(contextName); sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); break; } catch (NoSuchAlgorithmException e) { LOGGER.debug("SSLContext algorithm not available: " + contextName); } catch (Exception e) { LOGGER.debug("SSLContext can't be initialized: " + contextName, e); } } return sf; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private static SSLConnectionSocketFactory getSSLSocketFactory() { final TrustManager trustManager = new X509TrustManager() { @Override// w w w. j ava 2s . c o m public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); } catch (final NoSuchAlgorithmException e) { // should not happen // e.printStackTrace(); } catch (final KeyManagementException e) { // should not happen // e.printStackTrace(); } final SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); return sslSF; }
From source file:org.apache.ofbiz.base.util.UtilHttp.java
public static CloseableHttpClient getAllowAllHttpClient(String jksStoreFileName, String jksStorePassword) { try {/*from w ww . j av a2 s . co m*/ // Trust own CA and all self-signed certs SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(FileUtil.getFile(jksStoreFileName), jksStorePassword.toCharArray(), new TrustSelfSignedStrategy()).build(); // No host name verifier SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpClient; } catch (Exception e) { return HttpClients.createDefault(); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java
private Pair<String, String[]> loginAndGetJWT() throws Exception { CloseableHttpClient client = null;//from w w w.j a va 2 s . c o m try { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); URL loginURL = new URL(new URL(HOPSWORKS_ENDPOINT), HOPSWORKS_LOGIN_PATH); HttpUriRequest login = RequestBuilder.post().setUri(loginURL.toURI()) .addParameter("email", HOPSWORKS_USER).addParameter("password", HOPSWORKS_PASSWORD).build(); CloseableHttpResponse response = client.execute(login); Assert.assertNotNull(response); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Header[] authHeaders = response.getHeaders(HttpHeaders.AUTHORIZATION); String masterJWT = null; for (Header h : authHeaders) { Matcher matcher = HopsworksRMAppSecurityActions.JWT_PATTERN.matcher(h.getValue()); if (matcher.matches()) { masterJWT = matcher.group(1); } } JsonParser jsonParser = new JsonParser(); JsonObject json = jsonParser.parse(EntityUtils.toString(response.getEntity())).getAsJsonObject(); JsonArray array = json.getAsJsonArray("renewTokens"); String[] renewTokens = new String[array.size()]; boolean renewalTokensFound = false; for (int i = 0; i < renewTokens.length; i++) { renewTokens[i] = array.get(i).getAsString(); renewalTokensFound = true; } if (masterJWT != null && renewalTokensFound) { return new Pair<>(masterJWT, renewTokens); } throw new IOException("Could not get JWT from Hopsworks"); } finally { if (client != null) { client.close(); } } }
From source file:org.apache.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());/* w w w. j a v a2 s . c o m*/ } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.apache.http.conn.ssl.SSLConnectionSocketFactory.java
/** * Obtains default SSL socket factory with an SSL context based on the standard JSSE * trust material ({@code cacerts} file in the security properties directory). * System properties are not taken into consideration. * * @return default SSL socket factory//from w ww. j a v a2s. com */ public static SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationException { return new SSLConnectionSocketFactory(SSLContexts.createDefault(), getDefaultHostnameVerifier()); }
From source file:org.apache.syncope.installer.utilities.HttpUtils.java
private static CloseableHttpClient createHttpsClient() { CloseableHttpClient chc = null;/*from w w w. j a v a2 s. co m*/ try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); chc = HttpClients.custom().setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE)).build(); } catch (Exception ex) { // ignore } return chc; }