org.apache.http.conn.ssl.TrustSelfSignedStrategy Java Examples

The following examples show how to use org.apache.http.conn.ssl.TrustSelfSignedStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GetHTTP.java    From nifi with Apache License 2.0 8 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #2
Source File: PostHTTP.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example #3
Source File: ConnectionManager.java    From curly with Apache License 2.0 6 votes vote down vote up
private void createNewConnectionManager() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build(), NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslsf)
                .build();
        connectionManager = new PoolingHttpClientConnectionManager(r);
        connectionManager.setValidateAfterInactivity(500);
        sharedContext = ThreadLocal.withInitial(HttpClientContext::new);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example #4
Source File: SecurityUtils.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()//
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)//
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example #5
Source File: HttpsClientSslLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
    final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .build();
    final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();

    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    final CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLHostnameVerifier(hostnameVerifier)
        .setSSLSocketFactory(sslsf)
        .build();

    // new

    final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
    final HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));
    httpClient.close();

}
 
Example #6
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example #7
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 6 votes vote down vote up
public static void initPool() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
                Dict.HTTPS, sslsf).build();
        poolConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolConnManager.setMaxTotal(500);
        poolConnManager.setDefaultMaxPerRoute(200);
        int socketTimeout = 10000;
        int connectTimeout = 10000;
        int connectionRequestTimeout = 10000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                connectTimeout).build();
        httpClient = getConnection();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("init http client pool failed:", ex);
    }
}
 
Example #8
Source File: PacmanTableAPI.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static HttpResponse httpGenericMethod(String url) {
    HttpResponse response = null;
    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf).build();
        HttpGet httpGet = new HttpGet(url);
        response = httpclient.execute(httpGet);

    } catch (Exception e) {
        LOGGER.error("Error occured while http GET" , e);
    }
    return response;
}
 
Example #9
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #10
Source File: TLSHttpsTransport.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private SSLContext getSSLContext(KeyStore keyStore, String keyStoreValue, KeyStore trustStore) {
  try {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStoreValue.toCharArray());
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
    sslContext.init(keyManagers, trustManagers, new SecureRandom());
    return sslContext;
  } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example #11
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example #12
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory)
                    .build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Data.logger.warn("", e);
        }
        
        PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? 
                new PoolingHttpClientConnectionManager(socketFactoryRegistry):
                new PoolingHttpClientConnectionManager();
        
        // twitter specific options
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(200);
        
        return cm;
    }
 
Example #13
Source File: HttpUtils.java    From ScriptSpider with Apache License 2.0 6 votes vote down vote up
/**
 * 创建httpclient连接池并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example #14
Source File: BuildWorker.java    From anchore-container-scanner-plugin with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient makeHttpClient(boolean verify) {
  CloseableHttpClient httpclient = null;
  if (verify) {
    httpclient = HttpClients.createDefault();
  } else {
    //SSLContextBuilder builder;

    //SSLConnectionSocketFactory sslsf=null;

    try {
      SSLContextBuilder builder = new SSLContextBuilder();
      builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
          SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  return (httpclient);
}
 
Example #15
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example #16
Source File: AviRestUtils.java    From sdk with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient buildHttpClient(AviCredentials creds) {
	CloseableHttpClient httpClient = null;
	if (!creds.getVerify()) {
		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		} catch (Exception e) {
			e.printStackTrace();
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,
				(s, sslSession) -> true);

		httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
				.setSSLSocketFactory(sslConnectionSocketFactory)
				.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
						creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
				.build();
	} else {
		httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
				.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
						creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
				.build();
	}
	return httpClient;
}
 
Example #17
Source File: WireMockSpring.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
public static WireMockConfiguration options() {
	if (!initialized) {
		if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier",
				null)) {
			HttpsURLConnection
					.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
			try {
				HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
						.loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
						.build().getSocketFactory());
			}
			catch (Exception e) {
				throw new AssertionError("Cannot install custom socket factory: ["
						+ e.getMessage() + "]");
			}
		}
		initialized = true;
	}
	return new WireMockConfiguration();
}
 
Example #18
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 6 votes vote down vote up
public CustomHttpClient(String url, String user, String pass) throws Exception {
	this.openviduUrl = url.replaceFirst("/*$", "");
	this.headerAuth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes());

	SSLContext sslContext = null;
	try {
		sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return true;
			}
		}).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new Exception("Error building custom HttpClient: " + e.getMessage());
	}
	HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
			.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
	Unirest.setHttpClient(unsafeHttpClient);
}
 
Example #19
Source File: ApiHeadersTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpsDoesNotReturnJettyServerVersionHeader() throws Exception {

  final HttpGet httpget = new HttpGet(httpsUri +  "/test/endpoint");

  // trust all self-signed certs and add the client keystore if it's configured.
  final SSLContext sslContext = SSLContexts.custom()
      .loadTrustMaterial(new TrustSelfSignedStrategy())
      .loadKeyMaterial(new File(clientKeystoreLocation),SSL_PASSWORD.toCharArray(),
          SSL_PASSWORD.toCharArray())
      .build();

  final SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
      null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

  try ( CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslSf).build();
      CloseableHttpResponse response = httpclient.execute(httpget) ) {

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    assertThat(response.getFirstHeader( "Server" ), is(nullValue()));
  }
}
 
Example #20
Source File: AbstractRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
public AbstractRestTemplateClient ignoreAuthenticateServer() {
    //backward compatible with android httpclient 4.3.x
    if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier();
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer");
    }
    return this;
}
 
Example #21
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This method creates an insecure SSL factory that will trust on self signed certificates.
 * For that we use {@link TrustSelfSignedStrategy}.
 */
protected SSLConnectionSocketFactory createInsecureSslFactory() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());
        SSLContext sc = builder.build();

        if (acceptAllKindsOfCertificates) {
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager tm = new TrustAllManager();
            trustAllCerts[0] = tm;
            sc.init(null, trustAllCerts, null);

            HostnameVerifier hostnameVerifier = createInsecureHostNameVerifier();
            return new SSLConnectionSocketFactory(sc, hostnameVerifier);
        }
        return new SSLConnectionSocketFactory(sc);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example #22
Source File: StandardDirectorUtils.java    From chaos-lemur with Apache License 2.0 6 votes vote down vote up
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
        new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .useTLS()
        .build();

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create()
        .disableRedirectHandling()
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLSocketFactory(connectionFactory)
        .build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}
 
Example #23
Source File: ServerHttpsRequestIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.server.setHandler(new CheckRequestHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.port = this.server.getPort();

	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(new TrustSelfSignedStrategy());
	SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
			builder.build(), NoopHostnameVerifier.INSTANCE);
	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
			socketFactory).build();
	HttpComponentsClientHttpRequestFactory requestFactory =
			new HttpComponentsClientHttpRequestFactory(httpclient);
	this.restTemplate = new RestTemplate(requestFactory);
}
 
Example #24
Source File: HttpClientConfig.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
@Bean
public CloseableHttpClient httpClient() {
    try {
        //new ClassPathResource("").getURL()
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(keyStore, keyPassword.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}
 
Example #25
Source File: AppServicePacketTransport.java    From swellrt with Apache License 2.0 6 votes vote down vote up
private void httpConfig() {
  LOG.info("Setting up http Matrix Federation for id: " + userId);

  SSLContext sslcontext;

  try {
    sslcontext = SSLContexts.custom()
        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }

  CloseableHttpClient httpclient = HttpClients.custom()
      .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
      .setSSLContext(sslcontext)
      .build();
  Unirest.setHttpClient(httpclient);

  Unirest.setDefaultHeader("Content-Type","application/json");
}
 
Example #26
Source File: TagMeAnnotator.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void init() throws GerbilException {
    HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
        try {
            keyStore.load(instream, KEY_STORE_PASSWORD);
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
                .build();
        builder.setSSLContext(sslcontext);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
        CloseableHttpClient localClient = builder.build();
        this.setClient(localClient);
    } catch (Exception e) {
        throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
    }
    this.setClient(builder.build());
}
 
Example #27
Source File: ServerHttpsRequestIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.server.setHandler(new CheckRequestHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.port = this.server.getPort();

	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(new TrustSelfSignedStrategy());
	SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
			builder.build(), NoopHostnameVerifier.INSTANCE);
	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
			socketFactory).build();
	HttpComponentsClientHttpRequestFactory requestFactory =
			new HttpComponentsClientHttpRequestFactory(httpclient);
	this.restTemplate = new RestTemplate(requestFactory);
}
 
Example #28
Source File: ConfigureNameIdAction.java    From oxTrust with MIT License 5 votes vote down vote up
private String saveImpl() {
	AttributeResolverConfiguration attributeResolverConfiguration = new AttributeResolverConfiguration();
	attributeResolverConfiguration.setNameIdConfigs(this.nameIdConfigs);
	jsonConfigurationService.saveOxTrustAttributeResolverConfigurationConfiguration(attributeResolverConfiguration);
	boolean updateShib3Configuration = applicationConfiguration.isConfigGeneration();
	if (updateShib3Configuration) {
		List<GluuSAMLTrustRelationship> trustRelationships = trustService.getAllActiveTrustRelationships();
		if (!shibboleth3ConfService.generateConfigurationFiles(trustRelationships)) {
			log.error("Failed to update Shibboleth v3 configuration");
			facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to update Shibboleth v3 configuration");
		} else {
			try {
				SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy())
						.build();
				HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
				SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
						allowAllHosts);
				HttpClient client = HttpClients.custom()
						.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
						.setSSLSocketFactory(connectionFactory).build();
				HttpGet request = new HttpGet(
						"https://localhost/idp/profile/admin/reload-service?id=shibboleth.NameIdentifierGenerationService");
				request.addHeader("User-Agent", "Mozilla/5.0");
				HttpResponse response = client.execute(request);
				log.info(EntityUtils.toString(response.getEntity(), "UTF-8"));
			} catch (Exception e) {
				e.printStackTrace();
				log.error("error refreshing nameid setting (kindly restart services manually)", e);
			}
		}
	}

	return OxTrustConstants.RESULT_SUCCESS;
}
 
Example #29
Source File: UnsafeHttpsClient.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
public static HttpClient createUnsafeClient() {
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build());
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();

		return httpclient;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #30
Source File: AzkabanClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client.
 */
private CloseableHttpClient createHttpClient() throws AzkabanClientException {
  try {
  // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
  // Self sign SSL
  SSLContextBuilder sslcb = new SSLContextBuilder();
  sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

  HttpClientBuilder builder = HttpClientBuilder.create();
  RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
        .setSocketTimeout(10000)
        .setConnectTimeout(10000)
        .setConnectionRequestTimeout(10000)
        .build();

    builder.disableCookieManagement()
        .useSystemProperties()
        .setDefaultRequestConfig(requestConfig)
        .setConnectionManager(new BasicHttpClientConnectionManager())
        .setSSLSocketFactory(sslsf);

    return builder.build();
  } catch (Exception e) {
    throw new AzkabanClientException("HttpClient cannot be created", e);
  }
}