Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }//from   www . j a va  2s .  c  om

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);

    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}

From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java

private CloseableHttpClient getSSLBasedHTTPClient(String algo) throws Exception {

    File jks = findTrustedJKS();//from  ww  w . j a  v  a2 s.  c om

    KeyStore clientKeys = KeyStore.getInstance("JKS");
    clientKeys.load(new FileInputStream(jks.getCanonicalPath()), "password".toCharArray());

    // this is needed
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(clientKeys, new TrustSelfSignedStrategy())
            .loadKeyMaterial(clientKeys, "password".toCharArray()).build();

    // Host checking is disabled here , as tests might run on multiple hosts and
    // host entries can not be assumed
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    return httpclient;
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the request builder based on the request
 * /*from   w ww .  j  ava 2 s  .  c o  m*/
 * @param ssl The request SSL options
 * @param httpClientBuilder The request builder
 * @throws Exception
 */
private void setSSL(final SSL ssl, final HttpClientBuilder httpClientBuilder) throws Exception {
    if (ssl != null) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        if (ssl.getTrustStore() != null) {
            final KeyStore trustStore = ssl.getTrustStore().generateKeyStore();
            if (ssl.isUseSelfSignedCertificate()) {
                sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
            } else {
                sslContextBuilder.loadTrustMaterial(trustStore);
            }
        }

        if (ssl.getKeyStore() != null) {
            final KeyStore keyStore = ssl.getKeyStore().generateKeyStore();
            final String keyStorePassword = ssl.getKeyStore().getPassword();
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray());
        }

        sslContextBuilder.setSecureRandom(null);

        if (ssl.isUseTLS()) {
            sslContextBuilder.useTLS();
        } else {
            sslContextBuilder.useSSL();
        }

        final SSLVerifier verifier = ssl.getSslVerifier();
        X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
        switch (verifier) {
        case BROWSER:
            hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case ALLOW:
            hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        case STRICT:
            hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        default:
            hostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        }

        final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                sslContextBuilder.build(), hostnameVerifier);
        httpClientBuilder.setSSLSocketFactory(socketFactory);
    }
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String query2(String DMS_endpoint, String postObject)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override/* w ww. j ava  2  s. co  m*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy())
            .setSSLSocketFactory(sslSF).build();

    HttpPost postRequest = new HttpPost(dms_URL + "/" + DMS_endpoint);
    postRequest.addHeader("Content-Type", "application/json");
    postRequest.addHeader("vitalAccessToken", cookie.substring(17));

    HttpEntity entityPost = new StringEntity(postObject, StandardCharsets.UTF_8);
    postRequest.setEntity(entityPost);

    CloseableHttpResponse response = httpClient.execute(postRequest);

    try {
        //(CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(postRequest)) 
        //System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return null;
        return EntityUtils.toString(entity);
        //EntityUtils.consume(entity);
    } catch (IOException | ParseException e) {
        //logger.error(e.toString());
        //throw new ConnectionErrorException("Error in connection with DMSManager");
    }
    return null;
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected final CloseableHttpClient getHttpClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHttpClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(truststore), password.toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keystore), password.toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHttpServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//from w w  w  .j  ava  2 s  .c o  m

        if (sendHttpClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHttpClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

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 av  a2  s  .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:org.rundeck.api.ApiCall.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates
 *
 * @return an {@link HttpClient} instance - won't be null
 *///ww  w .j  a  v a  2s .co m
private CloseableHttpClient instantiateHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties();

    // configure user-agent
    httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion());

    if (client.isSslHostnameVerifyAllowAll()) {
        httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    if (client.isSslCertificateTrustAllowSelfSigned()) {
        // configure SSL
        try {
            httpClientBuilder.setSslcontext(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }
    if (client.isSystemProxyEnabled()) {
        // configure proxy (use system env : http.proxyHost / http.proxyPort)
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    }
    // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor
    httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (client.getToken() != null) {
                request.addHeader(AUTH_TOKEN_HEADER, client.getToken());
                //System.out.println("httpClient adding token header");
            } else if (client.getSessionID() != null) {
                request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID());
                //System.out.println("httpClient adding session header, sessionID="+client.getSessionID());
            }
        }
    });

    return httpClientBuilder.build();
}

From source file:net.geoprism.dashboard.DashboardMap.java

/**
 * Makes a getMap request to geoserver and returns the response as a ByteArrayOutputStream
 * //  w w  w  .  j a v  a 2 s. co m
 * @throws NoSuchAlgorithmException
 * 
 * @requestURL = geoserver getMap() or getLegendGraphic() request url
 */
private byte[] requestGeoserverImage(String requestURL) {
    InputStream inStream = null;
    ByteArrayOutputStream outStream = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        // StorePath and StorePass must be set for the systems keystore
        trustStore.load(new FileInputStream(GeoserverProperties.getGeoserverKeystorePath()),
                GeoserverProperties.getGeoserverKeystorePass().toCharArray());

        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(trustStore, GeoserverProperties.getGeoserverKeystorePass().toCharArray())
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();

        //
        // TODO: socket factory load once ever
        //
        SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        client = HttpClients.custom()
                // Allow all hostnames regardless of what is specified in the certificate
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                // Use the provided SSL socket factory
                .setSSLSocketFactory(factory)
                // Set a default cookie store which will be used in all of the requests
                .setDefaultCookieStore(new BasicCookieStore()).build();
        HttpGet method = new HttpGet(requestURL);
        response = client.execute(method);
        inStream = response.getEntity().getContent();
        outStream = new ByteArrayOutputStream();
        // Copy the input stream to the output stream
        IOUtils.copy(inStream, outStream);
    } catch (MalformedURLException e) {
        String error = "The URL is not formated correctly.";
        throw new ProgrammingErrorException(error, e);
    } catch (IOException e) {
        String error = "Could not make the request to the map server.";
        throw new ProgrammingErrorException(error, e);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }

        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                String error = "Could not close stream.";
                throw new ProgrammingErrorException(error, e);
            }
        }
    }

    return outStream.toByteArray();
}

From source file:org.finra.herd.dao.helper.HttpClientHelper.java

/**
 * Creates a new HTTP client./*  w w  w.jav  a 2 s  .c o m*/
 *
 * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate
 * @param disableHostnameVerification specifies whether to turn off hostname verification
 *
 * @return the HTTP client
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate,
        Boolean disableHostnameVerification)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    // Create an HTTP client builder.
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    // Create an SSL context builder.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    // If specified, setup a trust strategy that allows all certificates.
    if (BooleanUtils.isTrue(trustSelfSignedCertificate)) {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    }

    // If specified, turn hostname verification off.
    HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification)
            ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;

    // Create and assign an SSL connection socket factory.
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);

    // Build and return an HTTP client.
    return httpClientBuilder.build();
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/*from w  w  w .  j  a  v a2 s . c  o m*/
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            logger.error("Invalid deploy result code: {}", response.getStatusLine());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }
    } catch (IOException ioe) {
        logger.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
}