Search in sources :

Example 6 with Registry

use of org.apache.http.config.Registry in project dropwizard by dropwizard.

the class HttpClientBuilderTest method canUseACustomHostnameVerifierWhenTlsConfigurationNotSpecified.

@Test
void canUseACustomHostnameVerifierWhenTlsConfigurationNotSpecified() throws Exception {
    final HostnameVerifier customVerifier = (s, sslSession) -> false;
    final Registry<ConnectionSocketFactory> configuredRegistry;
    configuredRegistry = builder.using(customVerifier).createConfiguredRegistry();
    assertThat(configuredRegistry).isNotNull();
    final SSLConnectionSocketFactory socketFactory = (SSLConnectionSocketFactory) configuredRegistry.lookup("https");
    assertThat(socketFactory).isNotNull();
    final Field hostnameVerifierField = getInaccessibleField(SSLConnectionSocketFactory.class, "hostnameVerifier");
    assertThat(hostnameVerifierField.get(socketFactory)).isSameAs(customVerifier);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SocketAddress(java.net.SocketAddress) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SocketConfig(org.apache.http.config.SocketConfig) TlsConfiguration(io.dropwizard.client.ssl.TlsConfiguration) RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) ProxySelector(java.net.ProxySelector) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) Registry(org.apache.http.config.Registry) NTCredentials(org.apache.http.auth.NTCredentials) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) Proxy(java.net.Proxy) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) HttpHeaders(org.apache.http.HttpHeaders) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) InstrumentedHttpClientConnectionManager(com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager) LifecycleEnvironment(io.dropwizard.lifecycle.setup.LifecycleEnvironment) HeaderIterator(org.apache.http.HeaderIterator) HttpClientMetricNameStrategies(com.codahale.metrics.httpclient.HttpClientMetricNameStrategies) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) HttpRequest(org.apache.http.HttpRequest) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) Managed(io.dropwizard.lifecycle.Managed) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Optional(java.util.Optional) CredentialsProvider(org.apache.http.client.CredentialsProvider) Mockito.mock(org.mockito.Mockito.mock) DefaultRoutePlanner(org.apache.http.impl.conn.DefaultRoutePlanner) RegistryBuilder(org.apache.http.config.RegistryBuilder) BasicListHeaderIterator(org.apache.http.message.BasicListHeaderIterator) DnsResolver(org.apache.http.conn.DnsResolver) CookieSpecs(org.apache.http.client.config.CookieSpecs) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpRequestExecutor(org.apache.http.protocol.HttpRequestExecutor) Mockito.spy(org.mockito.Mockito.spy) Duration(io.dropwizard.util.Duration) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) ArgumentCaptor(org.mockito.ArgumentCaptor) Credentials(org.apache.http.auth.Credentials) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) HTTP(org.apache.http.protocol.HTTP) Nullable(javax.annotation.Nullable) Environment(io.dropwizard.setup.Environment) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MetricRegistry(com.codahale.metrics.MetricRegistry) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) IOException(java.io.IOException) HttpProcessor(org.apache.http.protocol.HttpProcessor) Mockito.when(org.mockito.Mockito.when) Field(java.lang.reflect.Field) Mockito.validateMockitoUsage(org.mockito.Mockito.validateMockitoUsage) Mockito.verify(org.mockito.Mockito.verify) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) RedirectStrategy(org.apache.http.client.RedirectStrategy) AfterEach(org.junit.jupiter.api.AfterEach) AuthScope(org.apache.http.auth.AuthScope) HttpContext(org.apache.http.protocol.HttpContext) BasicHeader(org.apache.http.message.BasicHeader) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) Field(java.lang.reflect.Field) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) Test(org.junit.jupiter.api.Test)

Example 7 with Registry

use of org.apache.http.config.Registry in project canal by alibaba.

the class AbstractRequest method executeHttpRequest.

/**
 * 执行http请求
 *
 * @param getMethod
 * @return
 * @throws IOException
 */
@SuppressWarnings("deprecation")
private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry registry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build();
    HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
    CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnPerRoute(50).setMaxConnTotal(100).setConnectionManager(httpClientConnectionManager).build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    getMethod.setConfig(requestConfig);
    HttpResponse response = httpClient.execute(getMethod);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
        String result = EntityUtils.toString(response.getEntity());
        throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
    }
    return response;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) Registry(org.apache.http.config.Registry) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 8 with Registry

use of org.apache.http.config.Registry in project ats-framework by Axway.

the class RestClient method constructRegistry.

private Registry constructRegistry() {
    try {
        SSLContextBuilder builder = SSLContextBuilder.create();
        builder.useProtocol(this.supportedProtocols[0]);
        if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
            builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(), clientConfigurator.getCertificateFilePassword()), clientConfigurator.getCertificateFilePassword().toCharArray());
        }
        // Trust all certificates
        builder.loadTrustMaterial(new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        Registry registry = RegistryBuilder.create().register("https", sslsf).build();
        return registry;
    } catch (Exception e) {
        throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
    }
}
Also used : TrustStrategy(org.apache.http.ssl.TrustStrategy) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) Registry(org.apache.http.config.Registry) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) RestException(com.axway.ats.action.exceptions.RestException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder)

Example 9 with Registry

use of org.apache.http.config.Registry in project wildfly by wildfly.

the class WebSecurityCERTTestCase method getHttpsClient.

private static CloseableHttpClient getHttpsClient(String alias) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        HostnameVerifier verifier = (string, ssls) -> true;
        //SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, verifier);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", ssf).build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        return HttpClientBuilder.create().setSSLSocketFactory(ssf).setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionManager(ccm).build();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) Arquillian(org.jboss.arquillian.junit.Arquillian) URL(java.net.URL) ServerSetup(org.jboss.as.arquillian.api.ServerSetup) RunWith(org.junit.runner.RunWith) TrustManager(javax.net.ssl.TrustManager) JBossJSSESecurityDomain(org.jboss.security.JBossJSSESecurityDomain) WebCERTTestsSecurityDomainSetup(org.jboss.as.test.integration.web.security.WebCERTTestsSecurityDomainSetup) StatusLine(org.apache.http.StatusLine) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) Registry(org.apache.http.config.Registry) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShrinkWrap(org.jboss.shrinkwrap.api.ShrinkWrap) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) CommonCriteria(org.jboss.as.test.categories.CommonCriteria) Test(org.junit.Test) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) Category(org.junit.experimental.categories.Category) KeyManager(javax.net.ssl.KeyManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpGet(org.apache.http.client.methods.HttpGet) Deployment(org.jboss.arquillian.container.test.api.Deployment) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpResponse(org.apache.http.HttpResponse) SecuredServlet(org.jboss.as.test.integration.web.security.SecuredServlet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ManagementClient(org.jboss.as.arquillian.container.ManagementClient) Assert.assertEquals(org.junit.Assert.assertEquals) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) JBossJSSESecurityDomain(org.jboss.security.JBossJSSESecurityDomain) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) KeyManager(javax.net.ssl.KeyManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 10 with Registry

use of org.apache.http.config.Registry in project pwm by pwm-project.

the class PwmHttpClient method getHttpClient.

public static HttpClient getHttpClient(final Configuration configuration, final PwmHttpClientConfiguration pwmHttpClientConfiguration) throws PwmUnrecoverableException {
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setUserAgent(PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION);
    final boolean httpClientPromiscuousEnable = Boolean.parseBoolean(configuration.readAppProperty(AppProperty.SECURITY_HTTP_PROMISCUOUS_ENABLE));
    try {
        if (httpClientPromiscuousEnable || (pwmHttpClientConfiguration != null && pwmHttpClientConfiguration.isPromiscuous())) {
            clientBuilder.setSSLContext(promiscuousSSLContext());
            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
        } else if (pwmHttpClientConfiguration != null && pwmHttpClientConfiguration.getCertificates() != null) {
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            final TrustManager trustManager = new X509Utils.CertMatchingTrustManager(configuration, pwmHttpClientConfiguration.getCertificates());
            sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
            final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionFactory).build();
            final HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            clientBuilder.setConnectionManager(ccm);
        }
    } catch (Exception e) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unexpected error creating promiscuous https client: " + e.getMessage()));
    }
    final String proxyUrl = configuration.readSettingAsString(PwmSetting.HTTP_PROXY_URL);
    if (proxyUrl != null && proxyUrl.length() > 0) {
        final URI proxyURI = URI.create(proxyUrl);
        final String host = proxyURI.getHost();
        final int port = proxyURI.getPort();
        clientBuilder.setProxy(new HttpHost(host, port));
        final String userInfo = proxyURI.getUserInfo();
        if (userInfo != null && userInfo.length() > 0) {
            final String[] parts = userInfo.split(":");
            final String username = parts[0];
            final String password = (parts.length > 1) ? parts[1] : "";
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(username, password));
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
            clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }
    }
    clientBuilder.setDefaultRequestConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(Integer.parseInt(configuration.readAppProperty(AppProperty.HTTP_CLIENT_SOCKET_TIMEOUT_MS))).setConnectTimeout(Integer.parseInt(configuration.readAppProperty(AppProperty.HTTP_CLIENT_CONNECT_TIMEOUT_MS))).setConnectionRequestTimeout(Integer.parseInt(configuration.readAppProperty(AppProperty.HTTP_CLIENT_REQUEST_TIMEOUT_MS))).build());
    return clientBuilder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SecureRandom(java.security.SecureRandom) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) Registry(org.apache.http.config.Registry) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) KeyStoreException(java.security.KeyStoreException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ErrorInformation(password.pwm.error.ErrorInformation) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) X509Utils(password.pwm.util.secure.X509Utils) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy)

Aggregations

Registry (org.apache.http.config.Registry)14 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)12 SSLContext (javax.net.ssl.SSLContext)10 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)10 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)10 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)9 IOException (java.io.IOException)8 RegistryBuilder (org.apache.http.config.RegistryBuilder)8 HttpResponse (org.apache.http.HttpResponse)6 HttpGet (org.apache.http.client.methods.HttpGet)6 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)6 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)6 URI (java.net.URI)5 HostnameVerifier (javax.net.ssl.HostnameVerifier)5 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)5 KeyManagementException (java.security.KeyManagementException)4 KeyStoreException (java.security.KeyStoreException)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 ProxySelector (java.net.ProxySelector)3 CertificateException (java.security.cert.CertificateException)3