org.apache.http.ssl.TrustStrategy Java Examples

The following examples show how to use org.apache.http.ssl.TrustStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractKeycloakIdentityProviderTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Rest template setup including a disabled SSL certificate validation.
 * @throws Exception in case of errors
 */
private static void setupRestTemplate() throws Exception {
	final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
               .loadTrustMaterial(null, acceptingTrustStrategy)
               .build();
	final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	final HttpClient httpClient = HttpClientBuilder.create()
    		.setRedirectStrategy(new LaxRedirectStrategy())
    		.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
    		.build();
	factory.setHttpClient(httpClient);
	restTemplate.setRequestFactory(factory);		

	for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
		if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
			restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
			break;
		}
	}
}
 
Example #2
Source File: HttpUtils.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLSocketFactory() {
        try {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
//			new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

            return socketFactory;
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
                    e);
        }
    }
 
Example #3
Source File: HttpHelper.java    From canal with Apache License 2.0 6 votes vote down vote up
public HttpHelper(){
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);

    // 创建支持忽略证书的https
    try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        httpclient = HttpClientBuilder.create()
            .setSSLContext(sslContext)
            .setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                .build()))
            .build();
    } catch (Throwable e) {
        // ignore
    }
}
 
Example #4
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient getCarelessHttpClient(boolean disableRedirect) {
    CloseableHttpClient httpClient = null;

    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
        HttpClientBuilder httpClientBuilder = HttpClients
                .custom()
                .setSSLSocketFactory(sslsf);
        if (disableRedirect) {
            httpClientBuilder.disableRedirectHandling();
        }
        httpClientBuilder.setUserAgent("swagger-validator");
        httpClient = httpClientBuilder.build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        LOGGER.error("can't disable SSL verification", e);
    }

    return httpClient;
}
 
Example #5
Source File: WebhookService.java    From webanno with Apache License 2.0 6 votes vote down vote up
public WebhookService()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
            String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy).build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

    nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
    nonValidatingRequestFactory.setHttpClient(httpClient);
}
 
Example #6
Source File: IftttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 6 votes vote down vote up
/**
 * This creates a HTTP client instance for connecting the IFTTT server.
 * 
 * @return the HTTP client instance
 */
private CloseableHttpClient buildHttpClient ()
{
    if ( configuration.isIftttIgnoreServerCertificate() ) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException
                {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }
        catch (Exception ex) {
            LOG.error(ex);
            // This should never happen, but we have to handle it
            throw new RuntimeException(ex);
        }
    }
    else {
        return HttpClients.createDefault();
    }
}
 
Example #7
Source File: HttpUtils.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLSocketFactory() {
        try {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
//			new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

            return socketFactory;
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
                    e);
        }
    }
 
Example #8
Source File: HttpClientUtils.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
 * but may be useful in certain testing or development scenarios.
 *
 * @return The SSLContext
 */
public static SSLContext buildCertificateIgnoringSslContext() {
	try {
		return SSLContexts
			.custom()
			.loadTrustMaterial(new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					return true;
				}
			})
			.build();
	}
	catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
	}
}
 
Example #9
Source File: GerritChecksApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritChecksApiBuilder allowInsecureHttps() {
  try {
    SSLContext sslContext =
        new SSLContextBuilder()
            .loadTrustMaterial(
                null,
                new TrustStrategy() {
                  public boolean isTrusted(final X509Certificate[] chain, String authType)
                      throws CertificateException {
                    return true;
                  }
                })
            .build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    clientBuilder.setSSLSocketFactory(sslsf);
  } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
    LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
  }
  return this;
}
 
Example #10
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #11
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #12
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #13
Source File: Util.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        log.error("Error in HttpUtil post ", e);
    }
    return httpClient;
}
 
Example #14
Source File: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient getHttpClient()
    throws IOException {
  try {
    // Self sign SSL
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // Create client
    return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore()).build();
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    throw new IOException("Issue with creating http client", e);
  }
}
 
Example #15
Source File: AzkabanClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client.
 */
private CloseableHttpClient createHttpClient() throws AzkabanClientException {
  try {
  // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
  // Self sign SSL
  SSLContextBuilder sslcb = new SSLContextBuilder();
  sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

  HttpClientBuilder builder = HttpClientBuilder.create();
  RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
        .setSocketTimeout(10000)
        .setConnectTimeout(10000)
        .setConnectionRequestTimeout(10000)
        .build();

    builder.disableCookieManagement()
        .useSystemProperties()
        .setDefaultRequestConfig(requestConfig)
        .setConnectionManager(new BasicHttpClientConnectionManager())
        .setSSLSocketFactory(sslsf);

    return builder.build();
  } catch (Exception e) {
    throw new AzkabanClientException("HttpClient cannot be created", e);
  }
}
 
Example #16
Source File: ApacheSyncClientExecutor.java    From BootNettyRpc with Apache License 2.0 5 votes vote down vote up
public void initialize(NettyRpcProperties properties, boolean https) throws Exception {
    CommonProperties cp = properties.getCommonProperties();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(Integer.parseInt(cp.getHttpConnectTimeout()))
            .setConnectionRequestTimeout(Integer.parseInt(cp.getHttpConnectRequestTimeout()))
            .setSocketTimeout(Integer.parseInt(cp.getHttpSocketTimeout()))
            .build();

    HttpClientBuilder clientBuilder = HttpClients.custom();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    if (https) {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
    }

    httpSyncClient = clientBuilder.build();

    LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
 
Example #17
Source File: HTTPInvoker.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
Example #18
Source File: HTTPInvoker.java    From product-iots with Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
Example #19
Source File: ApacheSyncClientExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public void initialize(ThunderProperties properties, boolean https) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setConnectionRequestTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setSocketTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
            .build();

    HttpClientBuilder clientBuilder = HttpClients.custom();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    if (https) {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
    }

    httpSyncClient = clientBuilder.build();

    LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
 
Example #20
Source File: Util.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient getHttpClient() {
	CloseableHttpClient httpClient = null;
	try {
		httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
				.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
					@Override
					public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
						return true;
					}
				}).build()).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		log.error("Error in HttpUtil post ", e);
	}
	return httpClient;
}
 
Example #21
Source File: HttpWebhookSender.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public HttpWebhookSender(String httpEndpoint, List<Header> headers, List<CDREventName> events) {
	this.httpEndpoint = httpEndpoint;
	this.events = events;

	this.customHeaders = new ArrayList<>();
	boolean contentTypeHeaderAdded = false;
	for (Header header : headers) {
		this.customHeaders.add(header);
		if (!contentTypeHeaderAdded && HttpHeaders.CONTENT_TYPE.equals(header.getName())
				&& "application/json".equals(header.getValue())) {
			contentTypeHeaderAdded = true;
		}
	}
	if (!contentTypeHeaderAdded) {
		this.customHeaders.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
	}

	TrustStrategy trustStrategy = new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			return true;
		}
	};

	SSLContext sslContext;

	try {
		sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new RuntimeException(e);
	}

	RequestConfig.Builder requestBuilder = RequestConfig.custom();
	requestBuilder = requestBuilder.setConnectTimeout(30000);
	requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);

	this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build())
			.setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
			.setSSLContext(sslContext).build();
}
 
Example #22
Source File: OpenVidu.java    From openvidu with Apache License 2.0 5 votes vote down vote up
/**
 * @param urlOpenViduServer Public accessible IP where your instance of OpenVidu
 *                          Server is up an running
 * @param secret            Secret used on OpenVidu Server initialization
 */
public OpenVidu(String hostname, String secret) {

	this.hostname = hostname;

	if (!this.hostname.endsWith("/")) {
		this.hostname += "/";
	}

	this.secret = secret;

	TrustStrategy trustStrategy = new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			return true;
		}
	};

	CredentialsProvider provider = new BasicCredentialsProvider();
	UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("OPENVIDUAPP", this.secret);
	provider.setCredentials(AuthScope.ANY, credentials);

	SSLContext sslContext;

	try {
		sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new RuntimeException(e);
	}

	RequestConfig.Builder requestBuilder = RequestConfig.custom();
	requestBuilder = requestBuilder.setConnectTimeout(30000);
	requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);

	this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build())
			.setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
			.setSSLContext(sslContext).setDefaultCredentialsProvider(provider).build();
}
 
Example #23
Source File: HttpUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #24
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }
 
Example #25
Source File: HttpPoolClient.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public  HttpClientConnectionManager createHttpClientConnectionManager() {
	SSLContext sslContext = null;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return false;
			}
		}).build();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
			NoopHostnameVerifier.INSTANCE);
	Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
			.build();
	PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
			socketFactoryRegistry);
	// 最大连接数
	poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getMaxTotal());
	// 单个站点最大连接数
	poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getMaxPerRoute());
	// 长连接
	poolingHttpClientConnectionManager.setDefaultSocketConfig(
			SocketConfig.custom().setSoTimeout(httpClientConfig.getSocketTimeout()).setSoKeepAlive(true).build());
	// 连接不活跃多久检查毫秒 并不是100 % 可信
	poolingHttpClientConnectionManager.setValidateAfterInactivity(httpClientConfig.getValidateAfterInactivity());
	// 空闲扫描线程
	HttpClientIdleConnectionMonitor.registerConnectionManager(poolingHttpClientConnectionManager, httpClientConfig);
	return poolingHttpClientConnectionManager;
}
 
Example #26
Source File: ApacheSyncClientExecutor.java    From distributed-limit with Apache License 2.0 5 votes vote down vote up
public void initialize(boolean https) throws Exception {

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(Integer.parseInt(HTTPCLIENT_CONNCT_TIMEOUT_DEFAULT))
                .setConnectionRequestTimeout(Integer.parseInt(HTTPCLIENT_CONNCT_REQUEST_TIMEOUT_DEFAULT))
                .setSocketTimeout(Integer.parseInt(HTTPCLIENT_SOCKET_TIMEOUT_DEFAULT))
                .build();

        HttpClientBuilder clientBuilder = HttpClients.custom();
        clientBuilder.setDefaultRequestConfig(requestConfig);

        if (https) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }

            }).build();
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
        }

        httpSyncClient = clientBuilder.build();

        LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
    }
 
Example #27
Source File: HttpClientUtils.java    From onetwo with Apache License 2.0 4 votes vote down vote up
private static HttpClient createHttpClient0(CookieStore cookieStore) throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException{
		RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
		ConnectionSocketFactory http = new PlainConnectionSocketFactory();
		registryBuilder.register("http", http);
		
		/*TrustManager trustManager = new X509TrustManager(){
			@Override
			public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
	  
			}
	  
			@Override
			public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
	  
			}
	  
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		}; */
		/***
		 * setConnectTimeout:设置连接超时时间,单位毫秒。
setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
		 */
		RequestConfig reqConfig = createDefaultRequestConfig();
		KeyStore trustStory = KeyStore.getInstance(KeyStore.getDefaultType());
		TrustStrategy anyTrustStrategy = new TrustStrategy(){
			@Override
			public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
				return true;
			}
		};
		SSLContext sslContext = SSLContexts.custom()
											.useProtocol("TLS")
											.loadTrustMaterial(trustStory, anyTrustStrategy)
											.build();
		LayeredConnectionSocketFactory https = new SSLConnectionSocketFactory(sslContext);
		registryBuilder.register("https", https);
		
		Registry<ConnectionSocketFactory> registry = registryBuilder.build();
		PoolingHttpClientConnectionManager poolMgr = new PoolingHttpClientConnectionManager(registry);
		return HttpClientBuilder.create()
								.setDefaultCookieStore(cookieStore)
								.setConnectionManager(poolMgr)
								.setDefaultRequestConfig(reqConfig)
								.build();
	}
 
Example #28
Source File: WebhookSink.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
CloseableHttpClient getHttpClient()  {

        // TODO: set a timeout until we have a proper way to deal with back pressure
        int timeout = 5;

        RequestConfig config = RequestConfig.custom()
          .setConnectTimeout(timeout * 1000)
          .setConnectionRequestTimeout(timeout * 1000)
          .setSocketTimeout(timeout * 1000).build();

        final TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) {
                return true;
            }
        };

	    try {

	        if(!verifySSL) {
	            return HttpClients.custom()
	                    .setSSLSocketFactory(
	                            new SSLConnectionSocketFactory(
	                                    new SSLContextBuilder()
	                                    .loadTrustMaterial(trustAllStrategy)
	                                    .build(),
	                                    NoopHostnameVerifier.INSTANCE))
	                    .setDefaultRequestConfig(config)
	                    .build();
	        }

	        if(effectiveTruststore == null) {
	            return HttpClients.custom()
                        .setDefaultRequestConfig(config)
                        .build();
	        }

		    return HttpClients.custom()
		            .setSSLSocketFactory(
		                    new SSLConnectionSocketFactory(
		                            new SSLContextBuilder()
		                            .loadTrustMaterial(effectiveTruststore, null)
		                            .build(),
		                            new DefaultHostnameVerifier()))
		            .setDefaultRequestConfig(config)
		            .build();


	    } catch(Exception ex) {
	    	log.error("Could not create HTTPClient due to {}, audit log not available.", ex.getMessage(), ex);
	    	return null;
	    }
	}
 
Example #29
Source File: AsyncHttpService.java    From Tenable.io-SDK-for-Java with MIT License 4 votes vote down vote up
private void initClient( String accessKey, String secretKey, List<Header> defaultHeadersOverride, String userAgent, int connectionRequestTimeout, int connectionTimeout, int socketTimeout, HttpHost proxy, boolean noSslValidation, String impersonateUsername ) {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    requestConfigBuilder.setConnectionRequestTimeout( connectionRequestTimeout ).setConnectTimeout( connectionTimeout ).setSocketTimeout( socketTimeout );
    if( proxy != null )
        requestConfigBuilder.setProxy( proxy );

    SSLContext sslContext = null;
    // Note: this block of code disables SSL validation. It is only used during development/testing when testing through a proxy
    if( noSslValidation ) {
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {
                    return true;
                }
            } )
                    .build();
        } catch( Exception e ) {
        }
    }

    //system properties
    Map<String, String> systemProperties = ManagementFactory.getRuntimeMXBean().getSystemProperties();

    if ( defaultHeadersOverride == null ) {
        if ( userAgent == null ) {
            userAgent = String.format( "TenableIOSDK Java/%s %s/%s/%s", systemProperties.get( "java.runtime.version" ), systemProperties.get( "os.name" ), systemProperties.get( "os.version" ), systemProperties.get( "os.arch" ) );
        }

        defaultHeaders = new ArrayList<>( 3 );
        defaultHeaders.add( new BasicHeader( "X-ApiKeys", String.format( "accessKey=%s; secretKey=%s", accessKey, secretKey ) ) );
        defaultHeaders.add( new BasicHeader( "User-Agent", userAgent ) );
        defaultHeaders.add( new BasicHeader( "Accept", "*/*" ) );

        if ( impersonateUsername != null ) {
            defaultHeaders.add( new BasicHeader( "X-Impersonate", "username=" + impersonateUsername ) );
        }
    } else {
        defaultHeaders = defaultHeadersOverride;
    }

    asyncClient = HttpAsyncClients.custom()
            .setDefaultRequestConfig( requestConfigBuilder.build() )
            .setDefaultHeaders( defaultHeaders )
            .setSSLContext( sslContext )
            .build();

    asyncClient.start();
}
 
Example #30
Source File: HttpClientUtils.java    From ais-sdk with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient acceptsUntrustedCertsHttpClient(boolean withProxy, ProxyHostInfo hostInfo, int connectionTimeout, int connectionRequestTimeout, int socketTimeout)
		throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	HttpClientBuilder b = HttpClientBuilder.create();
	
	/**
	 * set http proxy
	 */
	
	b.setDefaultRequestConfig( 
			RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build()
			);
	
	if(withProxy){
		HttpHost proxy=new HttpHost(hostInfo.getHostName(),hostInfo.getPort());
		b.setProxy(proxy);
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(proxy.getHostName(), proxy.getPort()),
				new UsernamePasswordCredentials(hostInfo.getUserName(), hostInfo.getPassword()));
		b.setDefaultCredentialsProvider(credsProvider);
	}
	
	SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, new TrustStrategy() {
		public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			return true;
		}
	}).build();
	b.setSSLContext(sslContext);
	b.setConnectionTimeToLive(180, TimeUnit.SECONDS);

	HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
	Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
			.build();

	PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
	connMgr.setMaxTotal(200);
	connMgr.setDefaultMaxPerRoute(100);
	b.setConnectionManager(connMgr);
	CloseableHttpClient client = b.build();
	return client;
}