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

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

Introduction

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

Prototype

public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException 

Source Link

Usage

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java

private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate,
        final CustomProxy customProxy) {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.useSystemProperties();
    if (!verifyCertificate) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {//from  w  w w  .j a  v  a 2 s.c  o m
            builder.loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build()));
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        }

    }
    if (customProxy != null) {
        Jenkins jenkins = PerfSigUIUtils.getInstance();
        if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) {
            final ProxyConfiguration proxyConfiguration = jenkins.proxy;
            if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) {
                httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port));
                if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                            proxyConfiguration.getUserName(), proxyConfiguration.getUserName());
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfiguration.name, proxyConfiguration.port),
                            usernamePasswordCredentials);
                    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        } else {
            httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort()));
            if (StringUtils.isNotBlank(customProxy.getProxyUser())
                    && StringUtils.isNotBlank(customProxy.getProxyPassword())) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                        customProxy.getProxyUser(), customProxy.getProxyPassword());
                credsProvider.setCredentials(
                        new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()),
                        usernamePasswordCredentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            }
        }
    }
    return httpClientBuilder;
}

From source file:org.wso2.greg.plugin.Utils.java

/**
 * Method to initialize the http client. We use only one instance of http client since there can not be concurrent
 * invocations//  w w w  . j  av  a  2s. co  m
 *
 * @return @link{HttpClient} httpClient instance
 */
public static HttpClient getHttpClient() {

    HttpClient httpClient = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();

    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to load the trust store", e);
    } catch (KeyStoreException e) {
        log.error("Unable to get the key store instance", e);
    } catch (KeyManagementException e) {
        log.error("Unable to load trust store material", e);
    }
    return httpClient;
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy//from  w  ww . j a v a 2  s. co  m
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

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

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP,
        int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from  ww  w . j a  v a 2 s  .  c  o  m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 *//*from  w  w  w .j  a  v a  2  s  . c o m*/
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", idpPort),
            new UsernamePasswordCredentials(user, password));

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
    try {
        trustStore.load(instream, "clientpass".toCharArray());
    } finally {
        try {
            instream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

    SSLContext sslContext = sslContextBuilder.build();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

    httpClient = httpClientBuilder.build();

    HttpGet httpget = new HttpGet(url);

    HttpResponse response = httpClient.execute(httpget);
    HttpEntity entity = response.getEntity();

    Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }

    //            Redirect to a POST is not supported without user interaction
    //            http://www.ietf.org/rfc/rfc2616.txt
    //            If the 301 status code is received in response to a request other
    //            than GET or HEAD, the user agent MUST NOT automatically redirect the
    //            request unless it can be confirmed by the user, since this might
    //            change the conditions under which the request was issued.

    Source source = new Source(EntityUtils.toString(entity));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    FormFields formFields = source.getFormFields();

    List<Element> forms = source.getAllElements(HTMLElementName.FORM);
    Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
    String postUrl = forms.get(0).getAttributeValue("action");

    Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
    Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

    for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
            nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
    }
    HttpPost httppost = new HttpPost(postUrl);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    response = httpClient.execute(httppost);

    entity = response.getEntity();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {// w ww. j a  v a  2s. com
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java

public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort)
        throws Exception {

    CloseableHttpClient httpClient = null;
    try {//from   ww  w .  j av  a2 s. com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Authorization", "Negotiate " + ticket);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * It builds a {@link SSLConnectionSocketFactory} if SSL is needed.
 * //from w w  w.  j av a2s  .c  o m
 * @return the {@link SSLConnectionSocketFactory} for SSL purposes.
 * @throws KeyManagementException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @see SSLConnectionSocketFactory
 */
private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    TrustStrategy ts = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // always true to avoid certificate unknown exception
            return true;
        }
    };
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, ts);
    SSLContext sslContext = builder.build();
    return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

/**
 * Utility method to send a slo request to a participant via GET message.
 * @param requestUrl/*from  w w w .  j a  va  2s. c o m*/
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
static void sendSLORequestToOtherParticipant(String requestUrl)
        throws URISyntaxException, ClientProtocolException, IOException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException {

    if (requestUrl == null || requestUrl.isEmpty())
        return;

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    URI httpUri = new URI(requestUrl);
    HttpGet httpGet = new HttpGet(httpUri);
    CloseableHttpResponse response = client.execute(httpGet);
    response.close();
}

From source file:com.muhardin.endy.training.ws.aplikasi.absen.rest.client.AbsenRestClient.java

public AbsenRestClient() {
    try {// w  w  w . ja  v  a  2s.c o m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("endy", "123");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setSSLSocketFactory(sslsf).build();

        restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
        restTemplate.setErrorHandler(new AbsenRestClientErrorHandler());
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(AbsenRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}