Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier.

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:io.hops.security.HopsUtil.java

/**
 * Set the default HTTPS trust policy to trust anything.
 *
 * NOTE: Use it only during development or use it wisely!
 *///from w  w  w  .  j  ava  2s.  co  m
public static void trustAllHTTPS() {
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustAll, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (GeneralSecurityException ex) {
        throw new IllegalStateException("Could not initialize SSLContext for CRL fetcher", ex);
    }
}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static JSONObject get(String url) throws IllegalStateException, SocketException,
        UnsupportedEncodingException, IOException, JSONException {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        return HTTPWrapper.parseResponse(response);
    } else {//  ww  w .java2 s .  c o  m
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Connects to the given url and returns the connection.
 * Caller should {@code connection.getInputStream().close()} the result of this
 * (especially if they are making heavy use of this method).
 *///  ww  w . jav a2  s  . co m
public static URLConnection connectToUrl(String u) throws Exception {
    final URL url = new URL(u);
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();

    // sometimes openConnection hangs, so run in background
    Future<URLConnection> f = executor.submit(new Callable<URLConnection>() {
        public URLConnection call() {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                URLConnection connection = url.openConnection();
                TrustingSslSocketFactory.configure(connection);
                connection.connect();

                connection.getContentLength(); // Make sure the connection is made.
                return connection;
            } catch (Exception e) {
                exception.set(e);
                LOG.debug("Error connecting to url " + url + " (propagating): " + e, e);
            }
            return null;
        }
    });
    try {
        URLConnection result = null;
        try {
            result = f.get(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Error connecting to url " + url + ", probably timed out (rethrowing): " + e);
            throw new IllegalStateException(
                    "Connect to URL not complete within 60 seconds, for url " + url + ": " + e);
        }
        if (exception.get() != null) {
            LOG.debug("Error connecting to url " + url + ", thread caller of " + exception,
                    new Throwable("source of rethrown error " + exception));
            throw exception.get();
        } else {
            return result;
        }
    } finally {
        f.cancel(true);
    }
}

From source file:org.ojbc.web.portal.services.SamlServiceImpl.java

Element retrieveAssertionFromShibboleth(HttpServletRequest request) throws Exception {
    // Note: pulled this straight from Andrew's demo JSP that displays the assertion and http request...

    /*/*from   w  w  w .  j a v a2 s  .  com*/
     *  fix for Exception in thread "main" javax.net.ssl.SSLHandshakeException:
     *       sun.security.validator.ValidatorException:
     *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
     *               unable to find valid certification path to requested target
     */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true; // andrew had this as false...dont know how that would work...
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
     * end of the fix
     */
    //Hard coded to pick up a single assertion...could loop through assertion headers if there will  be more than one
    String assertionHttpHeaderName = request.getHeader("Shib-Assertion-01");
    LOG.info("Loading assertion from: " + assertionHttpHeaderName);

    if (assertionHttpHeaderName == null) {
        LOG.warn("Shib-Assertion-01 header was null, Returning null asssertion document element");
        return null;
    }

    URL url = new URL(assertionHttpHeaderName);
    URLConnection con = url.openConnection();

    InputStream is = con.getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document assertionDoc = db.parse(is);

    return assertionDoc.getDocumentElement();

}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
 * Skip SSL certificate verification//from ww  w .j  ava  2s  .  com
 */
private void skipSslCertificateVerification() {
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    try {
        // get the SSL context object
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // initialize the SSL context
        sslContext.init(null, trustManager, new SecureRandom());

        // Set the default SSLSocketFactory
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    } catch (Exception e) {
    }
}

From source file:org.couchpotato.CouchPotato.java

private CouchPotato(String scheme, String hostname, int port, String path, String api, String username,
        String password, boolean trustAll, String trustMe) {
    this.scheme = scheme;
    this.hostName = hostname;
    this.port = port;
    this.path = path;
    this.api = api;
    this.username = username;
    this.password = password;
    this.trustAll = trustAll;

    if (this.username == null)
        this.username = "";
    if (this.password == null)
        this.password = "";

    // Configure SSL behavior based on user preferences
    Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
    HostnameVerifier verifier;/*from w  w  w .j  a va 2 s  .  co  m*/
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (NoSuchAlgorithmException e) {

    } catch (KeyManagementException e) {

    } catch (KeyStoreException e) {

    }
}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method sets up {@link HttpsURLConnection} so that no certificate or
 * hostname check is performed./*ww  w.  j a  v  a 2s.  c  om*/
 */
private void disableSSLChecks() {
    try {
        TrustManager trustAllCertificates = new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }
        };

        TrustManager[] trustAllCertificatesArray = { trustAllCertificates };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCertificatesArray, new java.security.SecureRandom());

        HostnameVerifier allHostsValid = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true; // I always say 'OK'
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new IllegalStateException("Something strange happened here", e);
    }
}

From source file:com.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java

private void setHostNameVerifierAndRoutePlanner(DefaultHttpClient httpClient) {

    // Use custom HostVerifier to accept our wildcard SSL Certificates: *.etilbudsavis.dk
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry);

    httpClient = new DefaultHttpClient(mgr, httpClient.getParams());

    // Change RoutePlanner to avoid SchemeRegistry causing IllegalStateException.
    // Some devices with faults in their default route planner
    httpClient.setRoutePlanner(new DefaultHttpRoutePlanner(registry));

    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

}

From source file:wptools.lib.Misc.java

/**
 * Bypass the normal SSL certificate authentication. If the passed
 * fingerprint is null, bypasses all authentication (dangerous).
 * Else trust anything whose chain contains a cert with the specified
 * fingerprint.//from  w  ww  .j a  v  a2  s  .  c  om
 * @param fing      Fingerprint
 */
public static void bypassSslAuth(final byte[] fing) {
    // Determine fingerprint type from its length
    final String type;
    if (fing == null) {
        type = null;
    } else {
        switch (fing.length) {
        case MD5_LEN:
            type = "MD5";
            break;
        case SHA1_LEN:
            type = "SHA-1";
            break;
        case SHA256_LEN:
            type = "SHA-256";
            break;
        default:
            throw new IllegalArgumentException("Invalid hash.");
        }
    }

    // Create a trust manager
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            matchFing(certs);
        }

        private void matchFing(X509Certificate[] certs) throws CertificateException {
            if (fing == null)
                return;
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(type);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }
            for (X509Certificate cert : certs) {
                md.reset();
                if (Arrays.equals(md.digest(cert.getEncoded()), fing))
                    return;
            }
            throw new CertificateException("No matching fingerprint found.");
        }
    } };

    // Install the trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    try {
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}