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

The following examples show how to use org.apache.http.conn.ssl.NoopHostnameVerifier. 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: AbstractKeycloakIdentityProviderTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Rest template setup including a disabled SSL certificate validation.
 * @throws Exception in case of errors
 */
private static void setupRestTemplate() throws Exception {
	final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
               .loadTrustMaterial(null, acceptingTrustStrategy)
               .build();
	final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	final HttpClient httpClient = HttpClientBuilder.create()
    		.setRedirectStrategy(new LaxRedirectStrategy())
    		.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
    		.build();
	factory.setHttpClient(httpClient);
	restTemplate.setRequestFactory(factory);		

	for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
		if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
			restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
			break;
		}
	}
}
 
Example #2
Source File: AdminApiKeyStoreTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient() throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
            KEYSTORE_TYPE,
            CLIENT_KEYSTORE_FILE_PATH,
            CLIENT_KEYSTORE_PW,
            KEYSTORE_TYPE,
            BROKER_TRUSTSTORE_FILE_PATH,
            BROKER_TRUSTSTORE_PW);

    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #3
Source File: HttpClientSteps.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Get secure http client implementation with trust all strategy and noop host name verifier.
 * @return
 */
private org.apache.http.client.HttpClient sslClient() {
    try {
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();

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

        return HttpClients
                .custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new CitrusRuntimeException("Failed to create http client for ssl connection", e);
    }
}
 
Example #4
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #5
Source File: CustomHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #6
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 #7
Source File: HttpClientBuilder.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try
    {
        KeyStore keyStore = KeyStoreUtil.createDockerKeyStore(certPath);

        SSLContext sslContext =
                SSLContexts.custom()
                           .setProtocol(SSLConnectionSocketFactory.TLS)
                           .loadKeyMaterial(keyStore, "docker".toCharArray())
                           .loadTrustMaterial(keyStore, null)
                           .build();
        String tlsVerify = System.getenv("DOCKER_TLS_VERIFY");
        SSLConnectionSocketFactory sslsf =
                tlsVerify != null && !tlsVerify.equals("0") && !tlsVerify.equals("false") ?
                        new SSLConnectionSocketFactory(sslContext) :
                        new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        return RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
    }
    catch (GeneralSecurityException e) {
        // this isn't ideal but the net effect is the same
        throw new IOException(e);
    }
}
 
Example #8
Source File: TemplateManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
CloseableHttpClient getHttpsClient()
{
    try
    {
        RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build();

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true );
        SSLConnectionSocketFactory sslSocketFactory =
                new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE );

        return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory )
                          .build();
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage() );
    }

    return HttpClients.createDefault();
}
 
Example #9
Source File: GerritChecksApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritChecksApiBuilder allowInsecureHttps() {
  try {
    SSLContext sslContext =
        new SSLContextBuilder()
            .loadTrustMaterial(
                null,
                new TrustStrategy() {
                  public boolean isTrusted(final X509Certificate[] chain, String authType)
                      throws CertificateException {
                    return true;
                  }
                })
            .build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    clientBuilder.setSSLSocketFactory(sslsf);
  } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
    LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
  }
  return this;
}
 
Example #10
Source File: CustomHttpClient.java    From zerocode-hello-world with MIT License 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #11
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
 * HEC.
 *
 * @param maxConnections max number of parallel connections.
 * @param disableCertificateValidation should disable certificate validation.
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example #12
Source File: SslTrustHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 * <p>
 * e.g. You can create your own project specific http client needed for http/https/tls connections.
 * Sometimes you may not need a SSLContext, sometimes you need one, some other times you need a
 * simple default http client e.g. HttpClients.createDefault() provided by Apache.
 * <p>
 * If you do not override this method, the framework creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    RequestConfig timeOutConfig = createMaxTimeOutConfig();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(timeOutConfig)
            .build();
}
 
Example #13
Source File: DefaultConsulConfigGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (agentConfig.trustStore.isPresent()) {
            sslContextBuilder = sslContextBuilder
                    .loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
        } else if (agentConfig.trustCerts) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
        }
        if (agentConfig.keyStore.isPresent()) {
            String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
            sslContextBuilder = sslContextBuilder.loadKeyMaterial(
                    readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
        }
        return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
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 #15
Source File: HunterRequest.java    From Burp-Hunter with GNU General Public License v3.0 6 votes vote down vote up
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        
        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
 
Example #16
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #17
Source File: AboutController.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
private String getChecksum(String defaultValue, String url,
		String version) {
	String result = defaultValue;
	if (result == null && StringUtils.hasText(url)) {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		url = constructUrl(url, version);
		try {
			ResponseEntity<String> response
					= new RestTemplate(requestFactory).exchange(
					url, HttpMethod.GET, null, String.class);
			if (response.getStatusCode().equals(HttpStatus.OK)) {
				result = response.getBody();
			}
		}
		catch (HttpClientErrorException httpException) {
			// no action necessary set result to undefined
			logger.debug("Didn't retrieve checksum because", httpException);
		}
	}
	return result;
}
 
Example #18
Source File: ODataUtil.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link HttpClientBuilder} for the given options.
 *
 * @return the new http client builder
 */
public static HttpClientBuilder createHttpClientBuilder(Map<String, Object> options) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    SSLContext sslContext = createSSLContext(options);
    if (sslContext != null) {
        // Skip verifying hostname
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
        builder.setSSLContext(sslContext);
        builder.setSSLHostnameVerifier(allowAllHosts);
    }

    CredentialsProvider credentialsProvider = createCredentialProvider(options);
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider).build();
    }

    return builder;
}
 
Example #19
Source File: ODataUtil.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link HttpClientBuilder} for the given options.
 *
 * @return the new http client builder
 */
public static HttpAsyncClientBuilder createHttpAsyncClientBuilder(Map<String, Object> options) {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();

    SSLContext sslContext = createSSLContext(options);
    if (sslContext != null) {
        // Skip verifying hostname
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
        builder.setSSLContext(sslContext);
        builder.setSSLHostnameVerifier(allowAllHosts);
    }

    CredentialsProvider credentialsProvider = createCredentialProvider(options);
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider).build();
    }

    return builder;
}
 
Example #20
Source File: AbstractNotifierConfig.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Gets an HTTP client that can be used to make requests.
 *
 * @return HTTP client
 */
public CloseableHttpClient getHttpClient(boolean ignoreSSL) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    if (ignoreSSL) {
        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                        .build()
        );
        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(connectionManager)
                .build();
    }
    return HttpClients.createDefault();
}
 
Example #21
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient noSslHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();

        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(
                        new PoolingHttpClientConnectionManager(
                                RegistryBuilder.<ConnectionSocketFactory>create()
                                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                                        .register("https", new SSLConnectionSocketFactory(sslContext,
                                                NoopHostnameVerifier.INSTANCE))
                                        .build()
                        ))
                .build();
    }
 
Example #22
Source File: AbstractHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
 
Example #23
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@code HostnameVerifier} given the provided {@code verification}.
 *
 * @param verification The intended hostname verification action.
 * @return A verifier for the request verification.
 * @throws IllegalArgumentException if the provided verification cannot be handled.
 */
HostnameVerifier getHostnameVerifier(HostnameVerification verification) {
  // Normally, the configuration logic would give us a default of STRICT if it was not
  // provided by the user. It's easy for us to do a double-check.
  if (verification == null) {
    verification = HostnameVerification.STRICT;
  }
  switch (verification) {
  case STRICT:
    return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
  case NONE:
    return NoopHostnameVerifier.INSTANCE;
  default:
    throw new IllegalArgumentException("Unhandled HostnameVerification: "
        + hostnameVerification);
  }
}
 
Example #24
Source File: AvaticaCommonsHttpClientImplTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
 
Example #25
Source File: SslTrustCorporateProxyHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client with Corporate Proxy, for both Http and Https connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    CredentialsProvider credsProvider = createProxyCredentialsProvider(proxyHost, proxyPort, proxyUserName, proxyPassword);

    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credsProvider)
            .setProxy(proxy)
            .build();
}
 
Example #26
Source File: HwYunMsgSender.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 获取CloseableHttpClient
 *
 * @return CloseableHttpClient
 */
private static CloseableHttpClient getHttpClient() {
    if (closeableHttpClient == null) {
        synchronized (HwYunMsgSender.class) {
            if (closeableHttpClient == null) {
                try {
                    // 为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
                    closeableHttpClient = HttpClients.custom()
                            .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                                    (x509CertChain, authType) -> true).build())
                            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                            .build();
                } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return closeableHttpClient;
}
 
Example #27
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 #28
Source File: HttpUtils.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLSocketFactory() {
        try {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
//			new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

            return socketFactory;
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
                    e);
        }
    }
 
Example #29
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient(String user) throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    X509Certificate trustCertificates[] = SecurityUtility.loadCertificatesFromPemFile(
            getTLSFile("ca.cert"));
    SSLContext sslCtx = SecurityUtility.createSslContext(
            false, trustCertificates,
            SecurityUtility.loadCertificatesFromPemFile(getTLSFile(user + ".cert")),
            SecurityUtility.loadPrivateKeyFromPemFile(getTLSFile(user + ".key-pk8")));
    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #30
Source File: ClickHouseHttpClientBuilder.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
private PoolingHttpClientConnectionManager getConnectionManager()
    throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory());

    if (properties.getSsl()) {
        HostnameVerifier verifier = "strict".equals(properties.getSslMode()) ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
        registry.register("https", new SSLConnectionSocketFactory(getSSLContext(), verifier));
    }

    //noinspection resource
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
        registry.build(),
        null,
        null,
        new IpVersionPriorityResolver(),
        properties.getTimeToLiveMillis(),
        TimeUnit.MILLISECONDS
    );

    connectionManager.setDefaultMaxPerRoute(properties.getDefaultMaxPerRoute());
    connectionManager.setMaxTotal(properties.getMaxTotal());
    connectionManager.setDefaultConnectionConfig(getConnectionConfig());
    return connectionManager;
}