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 File: HttpService.java    From oxAuth with 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 #2
Source File: ThriftOverHttp1Test.java    From armeria with 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 #3
Source File: CoreUtils.java    From oxd with 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 #4
Source File: DownloadServlet.java    From apicurio-studio with 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 #5
Source File: RestClientLiveManualTest.java    From tutorials with 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 #6
Source File: HttpsTest.java    From thorntail with 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 #7
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: HttpsClientSslLiveTest.java    From tutorials with 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 #9
Source File: HttpsClientSslLiveTest.java    From tutorials with 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 #10
Source File: TemplateManagerImpl.java    From peer-os with 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 #11
Source File: EsendexService.java    From JVoiceXML with 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 #12
Source File: HttpWorkflowStepPlugin.java    From rundeck-http-plugin with 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 #13
Source File: AbstractHttpClient.java    From Cognizant-Intelligent-Test-Scripter with 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 #14
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 6 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 #15
Source File: CrossOriginResourceSharingResponseTest.java    From s3proxy with 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 #16
Source File: SocketFactoryHttpClientFactory.java    From olingo-odata4 with 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 #17
Source File: DefaultApacheHttpClientBuilder.java    From weixin-java-tools with 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 #18
Source File: BaseTest.java    From oxAuth with 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 #19
Source File: HttpClientUtils.java    From frpMgr with 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 #20
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setBlindTrustSSLContext() {
    try {
        TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
        sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #21
Source File: RMRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setBlindTrustSSLContext() {
    try {
        TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
        sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #22
Source File: AcceptAllSocketFactory.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public AcceptAllSocketFactory() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    super(new TrustStrategy() {

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

    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
 
Example #23
Source File: SSLSessionStrategyFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file,
        final char[] tsp, final TrustStrategy trustStrategy)
                throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(file, "Truststore file"); //$NON-NLS-1$
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        trustStore.load(instream, tsp);
    } finally {
        instream.close();
    }
    return builder.loadTrustMaterial(trustStore, trustStrategy);
}
 
Example #24
Source File: CommonsDataLoader.java    From dss with 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);
	}
}
 
Example #25
Source File: GoAgentServerHttpClientBuilder.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();
    builder
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setTcpNoDelay(true)
                    .setSoKeepAlive(true)
                    .build()
            )
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    KeyStore keystore = agentKeystore();

    if (keystore != null) {
        sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
 
Example #26
Source File: AbstractRequest.java    From canal with 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 #27
Source File: HttpEventPublisher.java    From beam with 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 #28
Source File: RestClientLiveManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Ignore
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException {
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();

    final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;

    final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));

    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example #29
Source File: WebhookMsgHandler.java    From iotplatform with 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 #30
Source File: IndexerSingleton.java    From scava with 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;
}