List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER
X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
To view the source code for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.
Click Source Link
From source file:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java
private void startHttpClient() { if (httpClient != null) { // http client is already started return;//w w w . java 2 s .co m } // limit max number of async requests in sequential mode, 0 means "use // default limit" int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0; if (!disableCertificateValidation) { // create an http client that validates certificates httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).build(); } else { // create strategy that accepts all certificates TrustStrategy acceptingTrustStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] certificate, String type) { return true; } }; SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal) .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) .setSSLContext(sslContext).build(); } catch (Exception e) { } } httpClient.start(); }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Create a new client (with an explicit proxy and possibly transparent authentication) * /* www .j ava 2 s. c om*/ * @param aIdpUrl * the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP" * @param aUsername * the user name to log into the IdP. * @param aPassword * the password to log in to the IdP. * @param aProxy * if not {@code null}, use this proxy instead of the default system proxy (if any) * @param anyCert * if {@code true}, accept any certificate from any remote host. Otherwise, * certificates need to be installed in the JRE. * @param transparentAuth * if {@code true} (default), add a HttpRequestPostProcessor to transparently * authenticate. Otherwise, you must handle the authentication process yourself. */ public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert, boolean transparentAuth) { setIdpUrl(aIdpUrl); setUsername(aUsername); setPassword(aPassword); // Use a pooling connection manager, because we'll have to do a call out to the IdP // while still being in a connection with the SP PoolingHttpClientConnectionManager connMgr; if (anyCert) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()) .register("https", new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (GeneralSecurityException e) { // There shouldn't be any of these exceptions, because we do not use an actual // keystore throw new IllegalStateException(e); } } else { connMgr = new PoolingHttpClientConnectionManager(); } connMgr.setMaxTotal(10); connMgr.setDefaultMaxPerRoute(5); // The client needs to remember the auth cookie cookieStore = new BasicCookieStore(); RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); // Let's throw all common client elements into one builder object HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr) // The client needs to remember the auth cookie .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore) // Add the ECP/PAOS headers - needs to be added first so the cookie we get from // the authentication can be handled by the RequestAddCookies interceptor later .addInterceptorFirst(new HttpRequestPreprocessor()); // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default) if (transparentAuth) { customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor()); } // Build the client with/without proxy settings if (aProxy == null) { // use the proxy settings of the JVM, if specified client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build(); } else { // use the explicit proxy client = customClient.setProxy(aProxy).build(); } parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); }
From source file:com.floragunn.searchguard.httpclient.HttpClient.java
private final CloseableHttpClient createHTTPClient() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { // basic auth // pki auth/*from ww w . j av a2s .c o m*/ // kerberos auth final org.apache.http.impl.client.HttpClientBuilder hcb = HttpClients.custom(); if (ssl) { final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (log.isTraceEnabled()) { log.trace("Configure HTTP client with SSL"); } if (trustStore != null) { final KeyStore myTrustStore = KeyStore .getInstance(trustStore.getName().endsWith("jks") ? "JKS" : "PKCS12"); myTrustStore.load(new FileInputStream(trustStore), truststorePassword == null || truststorePassword.isEmpty() ? null : truststorePassword.toCharArray()); sslContextbBuilder.loadTrustMaterial(myTrustStore); } if (keystore != null) { final KeyStore keyStore = KeyStore .getInstance(keystore.getName().endsWith("jks") ? "JKS" : "PKCS12"); keyStore.load(new FileInputStream(keystore), keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); sslContextbBuilder.loadKeyMaterial(keyStore, keystorePassword == null || keystorePassword.isEmpty() ? null : keystorePassword.toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.1", "TLSv1.2" }, null, verifyHostnames ? SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } /*if (keytab != null) { //System.setProperty("java.security.auth.login.config", "login.conf"); //System.setProperty("java.security.krb5.conf", "krb5.conf"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new LoginSPNegoSchemeFactory(true); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); hcb.setDefaultCredentialsProvider(credsProvider); }*/ if (basicCredentials != null) { hcb.setDefaultHeaders( Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials))); } return hcb.build(); }
From source file:org.ow2.proactive.http.HttpClientBuilderTest.java
@Test public void testSystemPropertiesOverridenByProgrammaticSettings() { WebProperties.WEB_HTTPS_ALLOW_ANY_CERTIFICATE.updateProperty("true"); WebProperties.WEB_HTTPS_ALLOW_ANY_HOSTNAME.updateProperty("false"); WebProperties.storeInSystemProperties(); httpClientBuilder.useSystemProperties(true); httpClientBuilder.allowAnyCertificate(false); httpClientBuilder.allowAnyHostname(true); httpClientBuilder.build();/*from w w w .ja v a 2 s . c om*/ Mockito.verify(internalHttpClientBuilder).build(); Mockito.verify(internalHttpClientBuilder).useSystemProperties(); Mockito.verify(internalHttpClientBuilder, never()).setSslcontext(Mockito.<SSLContext>any()); Mockito.verify(internalHttpClientBuilder) .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }
From source file:com.github.tomakehurst.wiremock.HttpsAcceptanceTest.java
static String secureContentFor(String url, String clientTrustStore, String trustStorePassword) throws Exception { KeyStore trustStore = readKeyStore(clientTrustStore, trustStorePassword); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(trustStore, trustStorePassword.toCharArray()).useTLS().build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, // supported protocols null, // supported cipher suites SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpGet get = new HttpGet(url); HttpResponse response = httpClient.execute(get); String content = EntityUtils.toString(response.getEntity()); return content; }
From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java
/** Initialize the standard http poster. *///from w w w. j a va2s.c o m public HttpPoster(String protocol, String server, int port, String webapp, String core, int connectionTimeout, int socketTimeout, String updatePath, String removePath, String statusPath, String realm, String userID, String password, String allowAttributeName, String denyAttributeName, String idAttributeName, String modifiedDateAttributeName, String createdDateAttributeName, String indexedDateAttributeName, String fileNameAttributeName, String mimeTypeAttributeName, String contentAttributeName, IKeystoreManager keystoreManager, Long maxDocumentLength, String commitWithin, boolean useExtractUpdateHandler) throws ManifoldCFException { // These are the paths to the handlers in Solr that deal with the actions we need to do this.postUpdateAction = updatePath; this.postRemoveAction = removePath; this.postStatusAction = statusPath; this.commitWithin = commitWithin; this.allowAttributeName = allowAttributeName; this.denyAttributeName = denyAttributeName; this.idAttributeName = idAttributeName; this.modifiedDateAttributeName = modifiedDateAttributeName; this.createdDateAttributeName = createdDateAttributeName; this.indexedDateAttributeName = indexedDateAttributeName; this.fileNameAttributeName = fileNameAttributeName; this.mimeTypeAttributeName = mimeTypeAttributeName; this.contentAttributeName = contentAttributeName; this.useExtractUpdateHandler = useExtractUpdateHandler; this.maxDocumentLength = maxDocumentLength; String location = ""; if (webapp != null) location = "/" + webapp; if (core != null) { if (webapp == null) throw new ManifoldCFException("Webapp must be specified if core is specified."); location += "/" + core; } // Initialize standard solr-j. // First, we need an HttpClient where basic auth is properly set up. connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(1); SSLConnectionSocketFactory myFactory; if (keystoreManager != null) { myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } else { // Use the "trust everything" one myFactory = new SSLConnectionSocketFactory(KeystoreManagerFactory.getTrustingSecureSocketFactory(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout); HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setRedirectStrategy(new DefaultRedirectStrategy()).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()); if (userID != null && userID.length() > 0 && password != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); Credentials credentials = new UsernamePasswordCredentials(userID, password); if (realm != null) credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm), credentials); else credentialsProvider.setCredentials(AuthScope.ANY, credentials); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpClient localClient = clientBuilder.build(); String httpSolrServerUrl = protocol + "://" + server + ":" + port + location; solrServer = new ModifiedHttpSolrServer(httpSolrServerUrl, localClient, new XMLResponseParser()); }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java
private static PoolingHttpClientConnectionManager createConnManager() { String sslProtocolsStr = System.getProperty("https.protocols"); String cipherSuitesStr = System.getProperty("https.cipherSuites"); String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; if (SSL_INSECURE) { try {/*w w w. j a v a2s . co m*/ SSLContext sslContext = new SSLContextBuilder().useSSL() .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build(); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); if (PERSISTENT_POOL) { connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); connManager.setMaxTotal(MAX_CONN_TOTAL); } else { connManager.setMaxTotal(1); } return connManager; }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java
@SuppressWarnings("checkstyle:linelength") private static PoolingHttpClientConnectionManager createConnManager() { String sslProtocolsStr = System.getProperty("https.protocols"); String cipherSuitesStr = System.getProperty("https.cipherSuites"); String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; if (SSL_INSECURE) { try {// w w w . java2 s .c o m SSLContext sslContext = new SSLContextBuilder().useSSL() .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build(); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); if (persistentPool) { connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); connManager.setMaxTotal(MAX_CONN_TOTAL); } else { connManager.setMaxTotal(1); } return connManager; }
From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java
protected void getSession() throws ManifoldCFException, ServiceInterruption { if (hasBeenSetup == false) { String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL); if (emailAddress != null) userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; " + ((emailAddress == null) ? "" : emailAddress) + ")"; else// w ww .j ava 2s .c o m userAgent = null; String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL); if (protocol == null || protocol.length() == 0) protocol = "http"; String portString = params.getParameter(WikiConfig.PARAM_PORT); if (portString == null || portString.length() == 0) portString = null; String path = params.getParameter(WikiConfig.PARAM_PATH); if (path == null) path = "/w"; baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path + "/api.php?format=xml&"; int socketTimeout = 900000; int connectionTimeout = 300000; javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory .getTrustingSecureSocketFactory(); SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory( new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Set up connection manager connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (accessUser != null && accessUser.length() > 0 && accessPassword != null) { Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword); if (accessRealm != null && accessRealm.length() > 0) credentialsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials); else credentialsProvider.setCredentials(AuthScope.ANY, credentials); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { int proxyPortInt; if (proxyPort != null && proxyPort.length() > 0) { try { proxyPortInt = Integer.parseInt(proxyPort); } catch (NumberFormatException e) { throw new ManifoldCFException("Bad number: " + e.getMessage(), e); } } else proxyPortInt = 8080; // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPortInt), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPortInt); requestBuilder.setProxy(proxy); } httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).build(); /* BasicHttpParams params = new BasicHttpParams(); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true); params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout); params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true); DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params); // No retries localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { return false; } }); */ loginToAPI(); hasBeenSetup = true; } }