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 Project: nifi   Author: apache   File: GetHTTP.java    License: 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 Project: localization_nifi   Author: wangrenlei   File: PostHTTP.java    License: 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 Project: spring-analysis-note   Author: Vip-Augus   File: ServerHttpsRequestIntegrationTests.java    License: 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 #4
Source Project: java-technology-stack   Author: codeEngraver   File: ServerHttpsRequestIntegrationTests.java    License: 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 #5
Source Project: FATE-Serving   Author: FederatedAI   File: HttpClientPool.java    License: 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 #6
Source Project: pacbot   Author: tmobile   File: PacmanTableAPI.java    License: 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 #7
Source Project: localization_nifi   Author: wangrenlei   File: GetHTTP.java    License: 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 #8
Source Project: yacy_grid_mcp   Author: yacy   File: ClientConnection.java    License: 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 #9
Source Project: servicecomb-java-chassis   Author: apache   File: TLSHttpsTransport.java    License: 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 #10
Source Project: ScriptSpider   Author: xjtushilei   File: HttpUtils.java    License: 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 #11
Source Project: anchore-container-scanner-plugin   Author: jenkinsci   File: BuildWorker.java    License: 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 #12
Source Project: wildfly-camel-examples   Author: wildfly-extras   File: SecurityUtils.java    License: 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 #13
Source Project: sdk   Author: avinetworks   File: AviRestUtils.java    License: 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 #14
Source Project: spring-cloud-contract   Author: spring-cloud   File: WireMockSpring.java    License: 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 #15
Source Project: openvidu   Author: OpenVidu   File: CustomHttpClient.java    License: 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 #16
Source Project: documentum-rest-client-java   Author: Enterprise-Content-Management   File: AbstractRestTemplateClient.java    License: 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 #17
Source Project: apache-cloudstack-java-client   Author: Autonomiccs   File: ApacheCloudStackClient.java    License: 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 #18
Source Project: curly   Author: Adobe-Consulting-Services   File: ConnectionManager.java    License: 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 #19
Source Project: gerbil   Author: dice-group   File: TagMeAnnotator.java    License: 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 #20
Source Project: swellrt   Author: SwellRT   File: AppServicePacketTransport.java    License: 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 #21
Source Project: citrus-simulator   Author: citrusframework   File: HttpClientConfig.java    License: 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 #22
Source Project: chaos-lemur   Author: strepsirrhini-army   File: StandardDirectorUtils.java    License: 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 Project: rest-utils   Author: confluentinc   File: ApiHeadersTest.java    License: 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 #24
Source Project: tutorials   Author: eugenp   File: HttpsClientSslLiveTest.java    License: 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 #25
Source Project: wildfly-camel   Author: wildfly-extras   File: SecurityUtils.java    License: 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 #26
Source Project: keycloak   Author: keycloak   File: HttpUtil.java    License: 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 #27
Source Project: keycloak   Author: keycloak   File: HttpUtil.java    License: 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 #28
Source Project: pulsar-manager   Author: apache   File: HttpsClientConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CloseableHttpClient httpClient() throws Exception {
    if (tlsEnabled) {
        Resource resource = new FileSystemResource(tlsKeystore);
        File trustStoreFile = resource.getFile();
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStoreFile, tlsKeystorePassword.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = (s, sslSession) -> {
            // Custom logic to verify host name, tlsHostnameVerifier is false for test
            if (!tlsHostnameVerifier) {
                return true;
            } else {
                HostnameVerifier hv= HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify(s, sslSession);
            }
        };

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                hostnameVerifier);

        return HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
    }
    return HttpClients.custom().build();
}
 
Example #29
Source Project: cf-java-client-sap   Author: SAP   File: RestUtil.java    License: Apache License 2.0 5 votes vote down vote up
private javax.net.ssl.SSLContext buildSslContext() {
    try {
        return new SSLContextBuilder().useSSL()
                                      .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                                      .build();
    } catch (GeneralSecurityException gse) {
        throw new RuntimeException("An error occurred setting up the SSLContext", gse);
    }
}
 
Example #30
Source Project: ais-sdk   Author: huaweicloudsdk   File: AccessServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
	SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
			new AllowAllHostnameVerifier());

	return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
}