List of usage examples for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial
public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException
From source file:com.ibm.dataworks.DataLoadResource.java
/** * Create an HTTP client object that is authenticated with the user and password * of the IBM DataWorks Service.// www .j a v a 2 s . co m */ private HttpClient getAuthenticatedHttpClient() throws GeneralSecurityException { // NOTE: If you re-purpose this code for your own application you might want to have // additional security mechanisms in place regarding certificate authentication. // build credentials object UsernamePasswordCredentials creds = new UsernamePasswordCredentials(vcapInfo.getUser(), vcapInfo.getPassword()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds); // For demo purposes only: always accept the certificate TrustStrategy accepAllTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; SSLContextBuilder contextBuilder = new SSLContextBuilder(); SSLContext context = contextBuilder.loadTrustMaterial(null, accepAllTrustStrategy).build(); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, new AllowAllHostnameVerifier()); HttpClient httpClient = HttpClientBuilder.create() // .setSSLSocketFactory(scsf) // .setDefaultCredentialsProvider(credsProvider) // .build(); return httpClient; }
From source file:eu.vital.TrustManager.connectors.ppi.PPIManager.java
private String query(String ppi_endpoint, String body, String method) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { Cookie ck;/* ww w .j a v a2 s. c o m*/ //String internalToken; CloseableHttpClient httpclient; HttpRequestBase httpaction; //boolean wasEmpty; //int code; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); //httpclient = HttpClients.createDefault(); URI uri = null; try { // Prepare to forward the request to the proxy uri = new URI(ppi_endpoint); } catch (URISyntaxException e1) { //log } if (method.equals("GET")) { httpaction = new HttpGet(uri); } else { httpaction = new HttpPost(uri); } // Get token or authenticate if null or invalid //internalToken = client.getToken(); ck = new Cookie("vitalAccessToken", cookie.substring(17)); httpaction.setHeader("Cookie", ck.toString()); httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(3000) .setSocketTimeout(3000).build()); httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON); StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8); if (method.equals("POST")) { ((HttpPost) httpaction).setEntity(strEntity); } // Execute and get the response. CloseableHttpResponse response = null; try { response = httpclient.execute(httpaction); } catch (ClientProtocolException e) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, e); } catch (IOException e) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { // e1.printStackTrace(); } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000) .setConnectTimeout(7000).setSocketTimeout(7000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException ea) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, ea); return ""; } catch (IOException ea) { try { // Try again with a higher timeout try { Thread.sleep(1000); // do not retry immediately } catch (InterruptedException e1) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, e1); return ""; } httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000) .setConnectTimeout(12000).setSocketTimeout(12000).build()); response = httpclient.execute(httpaction); } catch (ClientProtocolException eaa) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } catch (Exception eaa) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; //return eaa.getMessage(); } } } int statusCode; try { statusCode = response.getStatusLine().getStatusCode(); } catch (Exception eaa) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa); return ""; } if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { if (statusCode == 503) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 503"); return ""; } else if (statusCode == 502) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 502"); return ""; } else if (statusCode == 401) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } else { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 500"); return ""; //throw new ServiceUnavailableException(); } } HttpEntity entity; entity = response.getEntity(); String respString = ""; if (entity != null) { try { respString = EntityUtils.toString(entity); response.close(); return respString; } catch (ParseException | IOException e) { java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401"); return ""; } } return respString; }
From source file:com.dnanexus.DXHTTPRequest.java
/** * Construct the DXHTTPRequest using the given DXEnvironment. *///from w ww . ja v a 2s . co m public DXHTTPRequest(DXEnvironment env) { this.securityContext = env.getSecurityContextJson(); this.apiserver = env.getApiserverPath(); this.disableRetry = env.isRetryDisabled(); SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } SSLConnectionSocketFactory sslSF = null; try { sslSF = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); String proxyHostS = System.getProperty("https.proxyHost"); String proxyPortS = System.getProperty("https.proxyPort"); if ((proxyHost == null || proxyPort == null) && (proxyHostS == null || proxyPortS == null)) { this.httpclient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); } else { HttpHost proxy = null; if (proxyHostS != null && proxyPortS != null) { proxy = new HttpHost(proxyHostS, Integer.parseInt(proxyPortS)); } else { proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); } httpClientBuilder.setProxy(proxy); HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner).setSSLSocketFactory(sslSF); httpclient = httpClientBuilder.setUserAgent(USER_AGENT).build(); } }
From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java
private SchemeSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { SSLContextBuilder builder = SSLContexts.custom().useTLS(); try {/*from ww w .ja v a2 s .c o m*/ builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } catch (KeyStoreException e) { log.error("Unable to set SSL trust manager: {}", e.getMessage(), e); } if (keyStore != null) { try { builder.loadKeyMaterial(keyStore, credentials.getPassword().toCharArray(), new PrivateKeyStrategy() { @Override public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) { return credentials.getUserPrincipal().getName(); } }); } catch (KeyStoreException | UnrecoverableKeyException e) { log.error("Unable to set SSL key manager: {}", e.getMessage(), e); } } return new SSLSocketFactory(builder.build(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }
From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java
/** * Builds the {@link SSLConnectionSocketFactory} used in the connection manager's socket factory registry. * * <p>Note that if {@link org.kuali.rice.ksb.util.KSBConstants.Config#KSB_ALLOW_SELF_SIGNED_SSL} is set to true * in the project configuration, this connection factory will be configured to accept self signed certs even if * the hostname doesn't match.</p> * * @return the SSLConnectionSocketFactory *///from w ww .j a va2s .co m protected SSLConnectionSocketFactory buildSslConnectionSocketFactory() { SSLContextBuilder builder = new SSLContextBuilder(); if (ConfigContext.getCurrentContextConfig() .getBooleanProperty(KSBConstants.Config.KSB_ALLOW_SELF_SIGNED_SSL)) { try { // allow self signed certs builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } catch (NoSuchAlgorithmException e) { throw new RiceRuntimeException(e); } catch (KeyStoreException e) { throw new RiceRuntimeException(e); } } SSLConnectionSocketFactory sslsf = null; try { if (ConfigContext.getCurrentContextConfig() .getBooleanProperty(KSBConstants.Config.KSB_ALLOW_SELF_SIGNED_SSL)) { // allow certs that don't match the hostname sslsf = new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); } else { sslsf = new SSLConnectionSocketFactory(builder.build()); } } catch (NoSuchAlgorithmException e) { throw new RiceRuntimeException(e); } catch (KeyManagementException e) { throw new RiceRuntimeException(e); } return sslsf; }
From source file:org.apache.stratos.integration.common.rest.RestClient.java
public RestClient() throws Exception { SSLContextBuilder builder = new SSLContextBuilder(); SSLConnectionSocketFactory sslConnectionFactory; builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslConnectionFactory = new SSLConnectionSocketFactory(builder.build()); this.httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionFactory) .setConnectionManager(HTTPConnectionManager.getInstance().getHttpConnectionManager()).build(); }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Create a new client (with an explicit proxy and possibly transparent authentication) * /*from ww w.j av a2 s . c o m*/ * @param aIdpUrl * the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP" * @param aUsername * the user name to log into the IdP. * @param aPassword * the password to log in to the IdP. * @param aProxy * if not {@code null}, use this proxy instead of the default system proxy (if any) * @param anyCert * if {@code true}, accept any certificate from any remote host. Otherwise, * certificates need to be installed in the JRE. * @param transparentAuth * if {@code true} (default), add a HttpRequestPostProcessor to transparently * authenticate. Otherwise, you must handle the authentication process yourself. */ public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert, boolean transparentAuth) { setIdpUrl(aIdpUrl); setUsername(aUsername); setPassword(aPassword); // Use a pooling connection manager, because we'll have to do a call out to the IdP // while still being in a connection with the SP PoolingHttpClientConnectionManager connMgr; if (anyCert) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()) .register("https", new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (GeneralSecurityException e) { // There shouldn't be any of these exceptions, because we do not use an actual // keystore throw new IllegalStateException(e); } } else { connMgr = new PoolingHttpClientConnectionManager(); } connMgr.setMaxTotal(10); connMgr.setDefaultMaxPerRoute(5); // The client needs to remember the auth cookie cookieStore = new BasicCookieStore(); RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); // Let's throw all common client elements into one builder object HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr) // The client needs to remember the auth cookie .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore) // Add the ECP/PAOS headers - needs to be added first so the cookie we get from // the authentication can be handled by the RequestAddCookies interceptor later .addInterceptorFirst(new HttpRequestPreprocessor()); // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default) if (transparentAuth) { customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor()); } // Build the client with/without proxy settings if (aProxy == null) { // use the proxy settings of the JVM, if specified client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build(); } else { // use the explicit proxy client = customClient.setProxy(aProxy).build(); } parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); }
From source file:org.apache.solr.util.SSLTestConfig.java
/** * Builds a new SSLContext for jetty servers which have been configured based on the settings of * this object./*from ww w .j a v a2 s .c o m*/ * * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking * due to lack of entropy, also explicitly allows the use of self-signed * certificates (since that's what is almost always used during testing). * almost always used during testing). */ public SSLContext buildServerSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { assert isSSLMode(); SSLContextBuilder builder = SSLContexts.custom(); builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE); builder.loadKeyMaterial(buildKeyStore(keyStore, getKeyStorePassword()), getKeyStorePassword().toCharArray()); if (isClientAuthMode()) { builder.loadTrustMaterial(buildKeyStore(trustStore, getTrustStorePassword()), new TrustSelfSignedStrategy()).build(); } return builder.build(); }
From source file:org.apache.solr.util.SSLTestConfig.java
/** * Builds a new SSLContext for HTTP <b>clients</b> to use when communicating with servers which have * been configured based on the settings of this object. * * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking * due to lack of entropy, also explicitly allows the use of self-signed * certificates (since that's what is almost always used during testing). */// ww w . j av a2 s . com public SSLContext buildClientSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { assert isSSLMode(); SSLContextBuilder builder = SSLContexts.custom(); builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE); // NOTE: KeyStore & TrustStore are swapped because they are from configured from server perspective... // we are a client - our keystore contains the keys the server trusts, and vice versa builder.loadTrustMaterial(buildKeyStore(keyStore, getKeyStorePassword()), new TrustSelfSignedStrategy()) .build(); if (isClientAuthMode()) { builder.loadKeyMaterial(buildKeyStore(trustStore, getTrustStorePassword()), getTrustStorePassword().toCharArray()); } return builder.build(); }