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

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

Introduction

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

Prototype

TrustStrategy

Source Link

Usage

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).
 * /*w w w.ja  v  a  2 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.wso2.mdm.qsg.utils.HTTPInvoker.java

private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

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

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

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

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

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}

From source file:de.hska.ld.content.client.PDFGenClient.java

private CloseableHttpClient createHttpsClient() throws IOException {
    SSLContext sslContext = null;
    try {/*from w  w  w .  j a v a  2  s  .  c  o  m*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        }).useProtocol("TLSv1.2").build();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return HttpClients.custom().setSSLContext(sslContext).build();
}

From source file:org.apache.camel.component.etcd.EtcdEndpoint.java

@Override
protected void doStart() throws Exception {
    if ((configuration.getTrustSelfsigned() == true) || (configuration.getCaFile() != null)
            || (configuration.getKeyFile() != null)) {
        // Need to create a custom httpclient since we need to change the SSL information.
        SSLContextBuilder builder = new SSLContextBuilder();
        if (configuration.getTrustSelfsigned() == true) {
            // Don't need to look at the CA file since we are going to trust anyhow.
            final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
                @Override//from  w  w  w.j  ava  2 s. co m
                public boolean isTrusted(X509Certificate[] certificate, String authType) {
                    return true;
                }
            };
            builder.loadTrustMaterial(acceptingTrustStrategy);
        } else {
            if (configuration.getCaFile() != null) {
                builder.loadTrustMaterial(new File(configuration.getCaFile()));
            }
        }
        // Now check if there are any private keys.
        if (configuration.getKeyFile() != null) {
            builder.loadKeyMaterial(new File(configuration.getKeyFile()), null, null);
        }
        //SSLSocketFactory socketfactory = SSLSocketFactory(builder.build());
        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().setSSLContext(builder.build())
                .build();
        etcdClient = new EtcdClient(configuration.makeURI());
    } else {
        etcdClient = new EtcdClient(configuration.makeURI());
    }
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///*from  w ww .  j  a va  2s  .c  o  m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // 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,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    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
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:org.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
 * but may be useful in certain testing or development scenarios.
 *
 * @return The SSLContext/*from  w w  w  . j  a  va  2  s  . co m*/
 */
public static SSLContext buildCertificateIgnoringSslContext() {
    try {
        return SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException(
                "Unexpected exception while building the certificate-ignoring SSLContext.", e);
    }
}

From source file:org.ow2.proactive.scheduling.api.graphql.service.AuthenticationService.java

@PostConstruct
protected void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    schedulerLoginFetchUrl = createLoginFetchUrl(schedulerRestUrl);

    sessionCache = CacheBuilder.newBuilder().maximumSize(Integer.parseInt(sessionCacheMaxSize))
            .expireAfterWrite(Integer.parseInt(sessionCacheExpireAfter), TimeUnit.MILLISECONDS)
            .build(new CacheLoader<String, String>() {
                @Override//from  w ww  . jav a 2 s .  com
                public String load(String sessionId) throws Exception {
                    return getLoginFromSessionId(sessionId);
                }
            });

    if (schedulerLoginFetchUrl.startsWith("https")) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(requestFactory);
    }

}

From source file:io.openvidu.java.client.OpenVidu.java

/**
 * @param urlOpenViduServer Public accessible IP where your instance of OpenVidu
 *                          Server is up an running
 * @param secret            Secret used on OpenVidu Server initialization
 *///from  w  w  w .j  av  a 2  s.  co m
public OpenVidu(String urlOpenViduServer, String secret) {

    OpenVidu.urlOpenViduServer = urlOpenViduServer;

    if (!OpenVidu.urlOpenViduServer.endsWith("/")) {
        OpenVidu.urlOpenViduServer += "/";
    }

    this.secret = secret;

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

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

    SSLContext sslContext;

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

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

    OpenVidu.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build())
            .setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .setSSLContext(sslContext).setDefaultCredentialsProvider(provider).build();
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>/*from  w w  w .  j  av a 2 s . com*/
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCClient.java

private AfdClient setSSLTrustPolicy(String domainControllerFQDN, int domainControllerPort)
        throws AuthException {
    try {//from  w  w  w . ja  va 2 s. c  o  m
        return new AfdClient(domainControllerFQDN, domainControllerPort, new DefaultHostnameVerifier(),
                new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }).build());

    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new AuthException("Failed to set SSL policy", e);
    }
}