org.apache.http.conn.ssl.TrustStrategy Java Examples

The following examples show how to use org.apache.http.conn.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 Project: armeria   Author: line   File: ThriftOverHttp1Test.java    License: Apache License 2.0 7 votes vote down vote up
@Override
protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException {
    final SSLContext sslContext;
    try {
        sslContext = SSLContextBuilder.create()
                                      .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
                                      .build();
    } catch (GeneralSecurityException e) {
        throw new TTransportException("failed to initialize an SSL context", e);
    }

    final THttpClient client = new THttpClient(
            uri, HttpClientBuilder.create()
                                  .setSSLHostnameVerifier((hostname, session) -> true)
                                  .setSSLContext(sslContext)
                                  .build());
    client.setCustomHeaders(
            headers.names().stream()
                   .collect(toImmutableMap(AsciiString::toString,
                                           name -> String.join(", ", headers.getAll(name)))));
    return client;
}
 
Example #2
Source Project: oxAuth   Author: GluuFederation   File: HttpService.java    License: MIT License 7 votes vote down vote up
public HttpClient getHttpsClientTrustAll() {
    try {
        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier());

        PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, psf));
        registry.register(new Scheme("https", 443, sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
        return new DefaultHttpClient(ccm);
    } catch (Exception ex) {
    	log.error("Failed to create TrustAll https client", ex);
        return new DefaultHttpClient();
    }
}
 
Example #3
Source Project: frpMgr   Author: Zo3i   File: HttpClientUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 创建 SSL连接
 */
public static CloseableHttpClient createSSLInsecureClient() {
	try {
		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return true;
			}
		}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		});
		return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	} catch (GeneralSecurityException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #4
Source Project: weixin-java-tools   Author: DarLiner   File: DefaultApacheHttpClientBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() {
  try {
    SSLContext sslcontext = SSLContexts.custom()
      //忽略掉对服务器端证书的校验
      .loadTrustMaterial(new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
          return true;
        }
      }).build();

    return new SSLConnectionSocketFactory(
      sslcontext,
      new String[]{"TLSv1"},
      null,
      SSLConnectionSocketFactory.getDefaultHostnameVerifier());
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    this.log.error(e.getMessage(), e);
  }

  return null;
}
 
Example #5
Source Project: Cognizant-Intelligent-Test-Scripter   Author: CognizantQAHub   File: AbstractHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        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);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
 
Example #6
Source Project: peer-os   Author: subutai-io   File: TemplateManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
CloseableHttpClient getHttpsClient()
{
    try
    {
        RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build();

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true );
        SSLConnectionSocketFactory sslSocketFactory =
                new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE );

        return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory )
                          .build();
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage() );
    }

    return HttpClients.createDefault();
}
 
Example #7
/**
 * Creates {@link HttpClient} that trusts any SSL certificate
 *
 * @return prepared HTTP client
 */
protected HttpClient getSSLAcceptingClient() {
	final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true;
	try {
		final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build();

		sslContext.init(null, getTrustManager(), new SecureRandom());
		final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
				new NoopHostnameVerifier());

		return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) {
		ConsoleUtils.printError(error.getMessage());
		throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error);
	}
}
 
Example #8
Source Project: thorntail   Author: thorntail   File: HttpsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void hello() throws IOException, GeneralSecurityException {
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
            .build();
    try (CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .build()) {

        String response = Executor.newInstance(httpClient)
                .execute(Request.Get("https://localhost:8443/"))
                .returnContent().asString();
        assertThat(response).contains("Hello on port 8443, secure: true");
    }
}
 
Example #9
Source Project: apicurio-studio   Author: Apicurio   File: DownloadServlet.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void postConstruct() {
    try {
        if (uiConfig.isDisableHubApiTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        logger.error("Error creating HTTP client.", e);
        throw new RuntimeException(e);
    }
}
 
Example #10
Source Project: JVoiceXML   Author: JVoiceXML   File: EsendexService.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public EsendexService(String user, String password, String account) {
		this.user = user;
		this.password = password;
		this.account = account;

		localContext = new BasicHttpContext();
		httpClient = new DefaultHttpClient();
		TrustStrategy easyStrategy = new TrustStrategy() {
			@Override
			public boolean isTrusted(
					java.security.cert.X509Certificate[] arg0, String arg1)
							throws CertificateException {
				return true;
			}
		};

		SSLSocketFactory socketFactory = null;
		try {
//			socketFactory = new SSLSocketFactory(easyStrategy);
		}  catch (Exception exception){
			logger.error(exception);
		}
//		Scheme sch = new Scheme("https", 443, socketFactory);
//		httpClient.getConnectionManager().getSchemeRegistry().register(sch);

	}
 
Example #11
Source Project: rundeck-http-plugin   Author: ohioit   File: HttpWorkflowStepPlugin.java    License: ISC License 6 votes vote down vote up
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException {
    SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(true).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) {
        log.debug("Disabling all SSL certificate verification.");
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });

        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
        httpClientBuilder.setSSLContext(sslContextBuilder.build());
    }

    return httpClientBuilder.build();
}
 
Example #12
Source Project: s3proxy   Author: gaul   File: CrossOriginResourceSharingResponseTest.java    License: Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient getHttpClient() throws
        KeyManagementException, NoSuchAlgorithmException,
        KeyStoreException {
    // Relax SSL Certificate check
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
            null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] arg0,
                        String arg1) throws CertificateException {
                    return true;
                }
            }).build();

    Registry<ConnectionSocketFactory> registry = RegistryBuilder
            .<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE)).build();

    PoolingHttpClientConnectionManager connectionManager = new
            PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(connectionManager)
            .build();
}
 
Example #13
Source Project: olingo-odata4   Author: apache   File: SocketFactoryHttpClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
  final TrustStrategy acceptTrustStrategy = new TrustStrategy() {
    @Override
    public boolean isTrusted(final X509Certificate[] certificate, final String authType) {
      return true;
    }
  };

  final SchemeRegistry registry = new SchemeRegistry();
  try {
    final SSLSocketFactory ssf =
            new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf));
  } catch (Exception e) {
    throw new ODataRuntimeException(e);
  }

  final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry));
  httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);

  return httpClient;
}
 
Example #14
Source Project: oxAuth   Author: GluuFederation   File: BaseTest.java    License: MIT License 6 votes vote down vote up
public static CloseableHttpClient createHttpClientTrustAll()
		throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
	SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			return true;
		}
	}).build();
	SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext);
	CloseableHttpClient httpclient = HttpClients.custom()
			.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
			.setSSLSocketFactory(sslContextFactory)
			.setRedirectStrategy(new LaxRedirectStrategy()).build();

	return httpclient;
}
 
Example #15
Source Project: oxd   Author: GluuFederation   File: CoreUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpClient createHttpClientTrustAll(Optional<ProxyConfiguration> proxyConfiguration) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException {

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }).build();
    //No operation verifier for trust All Client
    HostnameVerifier allowAllHosts = new HostnameVerifier() {

        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }

        public final String toString() {
            return "NO_OP";
        }
    };

    SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);

    return createClient(sslContextFactory, proxyConfiguration);
}
 
Example #16
Source Project: tutorials   Author: eugenp   File: HttpsClientSslLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
    final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
    
    final SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();

    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
    PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

    final CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setConnectionManager(clientConnectionManager)
            .build();

    final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
    final HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));

    httpClient.close();
}
 
Example #17
Source Project: tutorials   Author: eugenp   File: HttpsClientSslLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
    final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
    final SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy)
        .build();

    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

    final CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(sslsf)
        .build();

    final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
    final HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));

    httpClient.close();
}
 
Example #18
Source Project: tutorials   Author: eugenp   File: RestClientLiveManualTest.java    License: MIT License 6 votes vote down vote up
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {

    final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("https", sslsf)
            .register("http", new PlainConnectionSocketFactory())
            .build();

    final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    final CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setConnectionManager(connectionManager)
            .build();

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example #19
Source Project: browserup-proxy   Author: browserup   File: LittleProxyIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP client that trusts all upstream servers and uses a localhost proxy on the specified port.
 */
private static CloseableHttpClient getNewHttpClient(int proxyPort) {
    try {
        // Trust all certs -- under no circumstances should this ever be used outside of testing
        SSLContext sslcontext = SSLContexts.custom()
                .useTLS()
                .loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                })
                .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setProxy(new HttpHost("127.0.0.1", proxyPort))
                // disable decompressing content, since some tests want uncompressed content for testing purposes
                .disableContentCompression()
                .disableAutomaticRetries()
                .build();

        return httpclient;
    } catch (Exception e) {
        throw new RuntimeException("Unable to create new HTTP client", e);
    }
}
 
Example #20
Source Project: canal-1.1.3   Author: tianheframe   File: AbstractRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 执行http请求
 *
 * @param getMethod
 * @return
 * @throws IOException
 */
@SuppressWarnings("deprecation")
private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry registry = RegistryBuilder.create()
        .register("http", PlainConnectionSocketFactory.INSTANCE)
        .register("https", sslsf)
        .build();
    HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
    CloseableHttpClient httpClient = HttpClientBuilder.create()
        .setMaxConnPerRoute(50)
        .setMaxConnTotal(100)
        .setConnectionManager(httpClientConnectionManager)
        .build();
    RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout)
        .build();
    getMethod.setConfig(requestConfig);
    HttpResponse response = httpClient.execute(getMethod);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
        String result = EntityUtils.toString(response.getEntity());
        throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
    }
    return response;
}
 
Example #21
Source Project: super-cloudops   Author: wl4g   File: DockerRepositoryServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(httpClient);
    return factory;
}
 
Example #22
Source Project: document-management-software   Author: logicaldoc   File: HttpUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static CloseableHttpClient getNotValidatingClient(int timeout, String proxyServer, Integer proxyPort,
		String proxyUser, String proxyPassword) {
	try {
		HttpClientBuilder clientBuilder = HttpClients.custom();

		RequestConfig.Builder requestBuilder = RequestConfig.custom().setConnectTimeout(timeout * 1000)
				.setSocketTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000)
				.setRedirectsEnabled(true);

		if (StringUtils.isNotEmpty(proxyServer)) {
			HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
			requestBuilder.setProxy(proxyHost);

			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
			clientBuilder.setRoutePlanner(routePlanner);

			if (StringUtils.isNotEmpty(proxyUser)) {
				CredentialsProvider credentialProvider = new BasicCredentialsProvider();
				credentialProvider.setCredentials(AuthScope.ANY,
						new UsernamePasswordCredentials(proxyUser, proxyPassword));
				clientBuilder.setRoutePlanner(routePlanner);
			}
		}

		RequestConfig requestConfig = requestBuilder.build();

		CloseableHttpClient httpclient = clientBuilder.setHostnameVerifier(new AllowAllHostnameVerifier())
				.setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
					public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
						return true;
					}
				}).build()).setDefaultRequestConfig(requestConfig).build();
		return httpclient;
	} catch (Throwable t) {
		return null;
	}
}
 
Example #23
Source Project: DataflowTemplates   Author: GoogleCloudPlatform   File: HttpEventPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
 * HEC.
 *
 * @param maxConnections max number of parallel connections.
 * @param disableCertificateValidation should disable certificate validation.
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example #24
Source Project: ballerina-message-broker   Author: wso2-attic   File: HttpClientHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient prepareClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(factory);
    return builder.build();
}
 
Example #25
Source Project: java-pilosa   Author: pilosa   File: InsecurePilosaClientIT.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostName, SSLSession session) {
            return true;
        }
    };

    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        e.printStackTrace();
    }
    if (sslContext == null) {
        throw new RuntimeException("SSL Context not created");
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContext,
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example #26
Source Project: scava   Author: crossminer   File: ElasticSearchClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private boolean createClientDocker()
{
	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
	
	TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
	SSLContext sslContext;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
		
		RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
		
		restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				return httpClientBuilder;
			}
		});

		return createHighLevelClient(restClientBuilder);
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error("Error while creating secure connection to ElasticSearch: ", e);
	}
	
	return false;
}
 
Example #27
Source Project: scava   Author: crossminer   File: IndexerSingleton.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private boolean createClientDocker()
{
	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
	
	TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
	SSLContext sslContext;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
		
		RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
		
		restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				return httpClientBuilder;
			}
		});

		return createHighLevelClient(restClientBuilder);
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error("Error while creating secure connection to ElasticSearch: ", e);
	}
	
	return false;
}
 
Example #28
Source Project: iotplatform   Author: osswangxining   File: WebhookMsgHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static SSLContext createAcceptsAllCertsSSLContext()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
  return (new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
      return true;
    }
  }).build());
}
 
Example #29
Source Project: beam   Author: apache   File: HttpEventPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CloseableHttpClient} to make HTTP POSTs against Splunk's HEC.
 *
 * @param maxConnections max number of parallel connections
 * @param disableCertificateValidation should disable certificate validation
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example #30
Source Project: dss   Author: esig   File: CommonsDataLoader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
		final RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
	try {

		SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
		sslContextBuilder.setProtocol(sslProtocol);
		
		TrustStrategy trustStrategy = getTrustStrategy();
		if (trustStrategy != null) {
			LOG.debug("Set the TrustStrategy");
			sslContextBuilder.loadTrustMaterial(null, trustStrategy);
		}

		final KeyStore sslTrustStore = getSSLTrustStore();
		if (sslTrustStore != null) {
			LOG.debug("Set the SSL trust store as trust materials");
			sslContextBuilder.loadTrustMaterial(sslTrustStore, trustStrategy);
		}

		final KeyStore sslKeystore = getSSLKeyStore();
		if (sslKeystore != null) {
			LOG.debug("Set the SSL keystore as key materials");
			final char[] password = sslKeystorePassword != null ? sslKeystorePassword.toCharArray() : null;
			sslContextBuilder.loadKeyMaterial(sslKeystore, password);
			if (loadKeyStoreAsTrustMaterial) {
				LOG.debug("Set the SSL keystore as trust materials");
				sslContextBuilder.loadTrustMaterial(sslKeystore, trustStrategy);
			}
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), getSupportedSSLProtocols(),
				getSupportedSSLCipherSuites(), getHostnameVerifier());
		return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
	} catch (final Exception e) {
		throw new DSSException("Unable to configure the SSLContext/SSLConnectionSocketFactory", e);
	}
}