Example usage for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

List of usage examples for org.apache.http.ssl SSLContextBuilder SSLContextBuilder

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContextBuilder SSLContextBuilder.

Prototype

public SSLContextBuilder() 

Source Link

Usage

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientFactory.java

public static CloseableHttpClient getSSLClientFactory() throws Exception {

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        ///*from w w w  .  j av  a 2 s .  c om*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    return httpclient;
}

From source file:se.curity.examples.http.UnsafeHttpClientSupplier.java

private static HttpClient create() {
    try {/*from  ww  w.  ja  v  a  2 s  .c o m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().disableAuthCaching().disableAutomaticRetries().disableRedirectHandling()
                .setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        _logger.error("Unable to create Unsafe HTTP client supplier", e);
        throw new RuntimeException("Unable to initialize httpClient", e);
    }
}

From source file:org.eclipse.rdf4j.http.client.util.HttpClientBuilders.java

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 * //from www.  j  a  va2  s  .  c  om
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

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

        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.cloud.config.server.support.HttpClientSupport.java

public static HttpClientBuilder builder(HttpEnvironmentRepositoryProperties environmentProperties)
        throws GeneralSecurityException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    if (environmentProperties.isSkipSslValidation()) {
        sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }/*from w  w  w . j av  a 2s. c  o m*/

    if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
        ProxyHostProperties httpsProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTPS);
        ProxyHostProperties httpProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTP);

        httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
        httpClientBuilder
                .setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
    } else {
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        httpClientBuilder.setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider());
    }

    int timeout = environmentProperties.getTimeout() * 1000;
    return httpClientBuilder.setSSLContext(sslContextBuilder.build()).setDefaultRequestConfig(
            RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
}

From source file:org.geosamples.utilities.HTTPClient.java

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate.//www  . j  a  va2s.  c o m
 *
 * @see <a href="http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/">Tom's Blog</a>
 * @return CloseableHttpClient
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 */
public static CloseableHttpClient clientWithNoSecurityValidation()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    SSLContext sslContext = null;

    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true)
            .build();

    clientBuilder.setSSLContext(sslContext);

    // don't check Hostnames, either.
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    // 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);
    clientBuilder.setConnectionManager(connMgr);

    CloseableHttpClient httpClient = clientBuilder.build();

    return httpClient;
}

From source file:com.vmware.identity.rest.idm.client.test.integration.util.TestClientFactory.java

/**
 * Create an IdmClient with the given parameters.
 *
 * @param host address of the remote server
 * @param tenant name of the tenant/*  www . j av a 2  s .co  m*/
 * @param username username in UPN format
 * @param password password
 * @return IdmClient
 * @throws IOException
 * @throws ClientException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static IdmClient createClient(String host, String tenant, String username, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException,
        ClientException, IOException {
    HostRetriever hostRetriever = new SimpleHostRetriever(host, true);
    IdmClient client = new IdmClient(hostRetriever, NoopHostnameVerifier.INSTANCE,
            new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

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

    String token = TokenFactory.getAccessToken(host, tenant, username, password);

    client.setToken(new AccessToken(token, AccessToken.Type.JWT));
    return client;
}

From source file:com.vmware.directory.rest.client.test.integration.util.TestClientFactory.java

/**
 * Create an VmdirClient with the given parameters.
 *
 * @param host address of the remote server
 * @param tenant name of the tenant//from   w w w.j a v a  2  s .  c o  m
 * @param username username in UPN format
 * @param password password
 * @return IdmClient
 * @throws IOException
 * @throws ClientException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static VmdirClient createClient(String host, String tenant, String username, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException,
        ClientException, IOException {
    HostRetriever hostRetriever = new SimpleHostRetriever(host, true);
    VmdirClient client = new VmdirClient(hostRetriever, NoopHostnameVerifier.INSTANCE,
            new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

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

    String token = TokenFactory.getAccessToken(host, tenant, username, password);

    client.setToken(new AccessToken(token, AccessToken.Type.JWT));
    return client;
}

From source file:io.fabric8.elasticsearch.plugin.HttpsProxyClientCertAuthenticatorIntegrationTest.java

@Test
public void testProxyAuthWithSSL() throws Exception {
    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new File(keyStoreFile), keystorePW.toCharArray(), new TrustSelfSignedStrategy())
            .build();//from w ww  . j a va2 s  .  co  m

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }

            }).build()) {
        Executor ex = Executor.newInstance(httpclient);
        Response response = ex.execute(Request.Get("https://localhost:9200/blahobar.234324234/logs/1")
                .addHeader("Authorization", String.format("Bearer %s", token))
                .addHeader("X-Proxy-Remote-User", proxyUser));
        System.out.println(response.returnContent().asString());
    } catch (Exception e) {
        System.out.println(e);
        fail("Test Failed");
    }
}

From source file:sample.tomcat.SampleTomcatSslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("Hello, world", entity.getBody());
}

From source file:sample.tomcat.ssl.SampleTomcatSslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).isEqualTo("Hello, world");
}