Search in sources :

Example 1 with ProxyAuthenticationStrategy

use of org.apache.http.impl.client.ProxyAuthenticationStrategy in project hale by halestudio.

the class ClientProxyUtil method applyProxy.

/**
 * Set-up the given HTTP client to use the given proxy
 *
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    ProxyUtil.init();
    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);
        // $NON-NLS-1$
        String user = System.getProperty("http.proxyUser");
        // $NON-NLS-1$
        String password = System.getProperty("http.proxyPassword");
        boolean useProxyAuth = user != null && !user.isEmpty();
        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()), createCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider).setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }
        _log.trace(// $NON-NLS-1$ //$NON-NLS-2$
        "Set proxy to " + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + // $NON-NLS-1$ //$NON-NLS-2$
        ((useProxyAuth) ? (" as user " + user) : ("")));
    }
    return builder;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) InetSocketAddress(java.net.InetSocketAddress) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy)

Example 2 with ProxyAuthenticationStrategy

use of org.apache.http.impl.client.ProxyAuthenticationStrategy in project vorto by eclipse.

the class EidpUtils method proxyAuthenticatedRequestFactory.

public static ClientHttpRequestFactory proxyAuthenticatedRequestFactory(String proxyHost, int proxyPort, String proxyUser, String proxyPassword) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(proxyHost, proxyPort));
    clientBuilder.setDefaultCredentialsProvider(credsProvider);
    clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    CloseableHttpClient client = clientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(client);
    return factory;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy)

Example 3 with ProxyAuthenticationStrategy

use of org.apache.http.impl.client.ProxyAuthenticationStrategy in project vorto by eclipse.

the class ConfigProxied method restTemplate.

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(proxyHost, proxyPort));
    clientBuilder.setDefaultCredentialsProvider(credsProvider);
    clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    CloseableHttpClient client = clientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(client);
    restTemplate.setRequestFactory(factory);
    return restTemplate;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) RestTemplate(org.springframework.web.client.RestTemplate) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy) Bean(org.springframework.context.annotation.Bean)

Example 4 with ProxyAuthenticationStrategy

use of org.apache.http.impl.client.ProxyAuthenticationStrategy in project cerberus-source by cerberustesting.

the class RestService method callREST.

@Override
public AnswerItem<AppService> callREST(String servicePath, String requestString, String method, List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs, String system) {
    AnswerItem result = new AnswerItem();
    AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "", "", "", null, "", null);
    serviceREST.setProxy(false);
    serviceREST.setProxyHost(null);
    serviceREST.setProxyPort(0);
    serviceREST.setProxyWithCredential(false);
    serviceREST.setProxyUser(null);
    serviceREST.setTimeoutms(timeOutMs);
    MessageEvent message = null;
    if (StringUtil.isNullOrEmpty(servicePath)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtil.isNullOrEmpty(method)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING);
        result.setResultMessage(message);
        return result;
    }
    // If token is defined, we add 'cerberus-token' on the http header.
    if (!StringUtil.isNullOrEmpty(token)) {
        headerList.add(factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));
    }
    CloseableHttpClient httpclient;
    if (proxyService.useProxy(servicePath, system)) {
        String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
        int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);
        serviceREST.setProxy(true);
        serviceREST.setProxyHost(proxyHost);
        serviceREST.setProxyPort(proxyPort);
        HttpHost proxyHostObject = new HttpHost(proxyHost, proxyPort);
        if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {
            String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);
            String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);
            serviceREST.setProxyWithCredential(true);
            serviceREST.setProxyUser(proxyUser);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
            LOG.debug("Activating Proxy With Authentification.");
            httpclient = HttpClientBuilder.create().setProxy(proxyHostObject).setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()).setDefaultCredentialsProvider(credsProvider).build();
        } else {
            LOG.debug("Activating Proxy (No Authentification).");
            httpclient = HttpClientBuilder.create().setProxy(proxyHostObject).build();
        }
    } else {
        httpclient = HttpClients.createDefault();
    }
    try {
        RequestConfig requestConfig;
        // Timeout setup.
        requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).setConnectionRequestTimeout(timeOutMs).setSocketTimeout(timeOutMs).build();
        AppService responseHttp = null;
        switch(method) {
            case AppService.METHOD_HTTPGET:
                LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString);
                // Adding query string from requestString
                servicePath = StringUtil.addQueryString(servicePath, requestString);
                // Adding query string from contentList
                String newRequestString = AppServiceService.convertContentListToQueryString(contentList);
                servicePath = StringUtil.addQueryString(servicePath, newRequestString);
                serviceREST.setServicePath(servicePath);
                HttpGet httpGet = new HttpGet(servicePath);
                // Timeout setup.
                httpGet.setConfig(requestConfig);
                // Header.
                if (headerList != null) {
                    for (AppServiceHeader contentHeader : headerList) {
                        httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue());
                    }
                }
                serviceREST.setHeaderList(headerList);
                // Saving the service before the call Just in case it goes wrong (ex : timeout).
                result.setItem(serviceREST);
                LOG.info("Executing request " + httpGet.getRequestLine());
                responseHttp = executeHTTPCall(httpclient, httpGet);
                if (responseHttp != null) {
                    serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                    serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                    serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                    serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
                }
                break;
            case AppService.METHOD_HTTPPOST:
                LOG.info("Start preparing the REST Call (POST). " + servicePath);
                serviceREST.setServicePath(servicePath);
                HttpPost httpPost = new HttpPost(servicePath);
                // Timeout setup.
                httpPost.setConfig(requestConfig);
                // Content
                if (!(StringUtil.isNullOrEmpty(requestString))) {
                    // If requestString is defined, we POST it.
                    InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
                    InputStreamEntity reqEntity = new InputStreamEntity(stream);
                    reqEntity.setChunked(true);
                    httpPost.setEntity(reqEntity);
                    serviceREST.setServiceRequest(requestString);
                } else {
                    // If requestString is not defined, we POST the list of key/value request.
                    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                    for (AppServiceContent contentVal : contentList) {
                        nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
                    serviceREST.setContentList(contentList);
                }
                // Header.
                for (AppServiceHeader contentHeader : headerList) {
                    httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue());
                }
                serviceREST.setHeaderList(headerList);
                // Saving the service before the call Just in case it goes wrong (ex : timeout).
                result.setItem(serviceREST);
                LOG.info("Executing request " + httpPost.getRequestLine());
                responseHttp = executeHTTPCall(httpclient, httpPost);
                if (responseHttp != null) {
                    serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                    serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                    serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                    serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
                } else {
                    message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                    message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
                    message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
                    result.setResultMessage(message);
                    return result;
                }
                break;
            case AppService.METHOD_HTTPDELETE:
                LOG.info("Start preparing the REST Call (DELETE). " + servicePath);
                servicePath = StringUtil.addQueryString(servicePath, requestString);
                serviceREST.setServicePath(servicePath);
                HttpDelete httpDelete = new HttpDelete(servicePath);
                // Timeout setup.
                httpDelete.setConfig(requestConfig);
                // Header.
                for (AppServiceHeader contentHeader : headerList) {
                    httpDelete.addHeader(contentHeader.getKey(), contentHeader.getValue());
                }
                serviceREST.setHeaderList(headerList);
                // Saving the service before the call Just in case it goes wrong (ex : timeout).
                result.setItem(serviceREST);
                LOG.info("Executing request " + httpDelete.getRequestLine());
                responseHttp = executeHTTPCall(httpclient, httpDelete);
                if (responseHttp != null) {
                    serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                    serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                    serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                    serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
                }
                break;
            case AppService.METHOD_HTTPPUT:
                LOG.info("Start preparing the REST Call (PUT). " + servicePath);
                serviceREST.setServicePath(servicePath);
                HttpPut httpPut = new HttpPut(servicePath);
                // Timeout setup.
                httpPut.setConfig(requestConfig);
                // Content
                if (!(StringUtil.isNullOrEmpty(requestString))) {
                    // If requestString is defined, we POST it.
                    InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
                    InputStreamEntity reqEntity = new InputStreamEntity(stream);
                    reqEntity.setChunked(true);
                    httpPut.setEntity(reqEntity);
                    serviceREST.setServiceRequest(requestString);
                } else {
                    // If requestString is not defined, we PUT the list of key/value request.
                    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                    for (AppServiceContent contentVal : contentList) {
                        nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
                    }
                    httpPut.setEntity(new UrlEncodedFormEntity(nvps));
                    serviceREST.setContentList(contentList);
                }
                // Header.
                for (AppServiceHeader contentHeader : headerList) {
                    httpPut.addHeader(contentHeader.getKey(), contentHeader.getValue());
                }
                serviceREST.setHeaderList(headerList);
                // Saving the service before the call Just in case it goes wrong (ex : timeout).
                result.setItem(serviceREST);
                LOG.info("Executing request " + httpPut.getRequestLine());
                responseHttp = executeHTTPCall(httpclient, httpPut);
                if (responseHttp != null) {
                    serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                    serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                    serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                    serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
                } else {
                    message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                    message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
                    message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
                    result.setResultMessage(message);
                    return result;
                }
                break;
            case AppService.METHOD_HTTPPATCH:
                LOG.info("Start preparing the REST Call (PUT). " + servicePath);
                serviceREST.setServicePath(servicePath);
                HttpPatch httpPatch = new HttpPatch(servicePath);
                // Timeout setup.
                httpPatch.setConfig(requestConfig);
                // Content
                if (!(StringUtil.isNullOrEmpty(requestString))) {
                    // If requestString is defined, we POST it.
                    InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
                    InputStreamEntity reqEntity = new InputStreamEntity(stream);
                    reqEntity.setChunked(true);
                    httpPatch.setEntity(reqEntity);
                    serviceREST.setServiceRequest(requestString);
                } else {
                    // If requestString is not defined, we PUT the list of key/value request.
                    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                    for (AppServiceContent contentVal : contentList) {
                        nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
                    }
                    httpPatch.setEntity(new UrlEncodedFormEntity(nvps));
                    serviceREST.setContentList(contentList);
                }
                // Header.
                for (AppServiceHeader contentHeader : headerList) {
                    httpPatch.addHeader(contentHeader.getKey(), contentHeader.getValue());
                }
                serviceREST.setHeaderList(headerList);
                // Saving the service before the call Just in case it goes wrong (ex : timeout).
                result.setItem(serviceREST);
                LOG.info("Executing request " + httpPatch.getRequestLine());
                responseHttp = executeHTTPCall(httpclient, httpPatch);
                if (responseHttp != null) {
                    serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                    serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                    serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                    serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
                } else {
                    message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                    message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
                    message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
                    result.setResultMessage(message);
                    return result;
                }
                break;
        }
        // Get result Content Type.
        if (responseHttp != null) {
            serviceREST.setResponseHTTPBodyContentType(AppServiceService.guessContentType(serviceREST, AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON));
        }
        result.setItem(serviceREST);
        message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", method));
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath));
        result.setResultMessage(message);
    } catch (SocketTimeoutException ex) {
        LOG.info("Exception when performing the REST Call. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_TIMEOUT);
        message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath));
        message.setDescription(message.getDescription().replace("%TIMEOUT%", String.valueOf(timeOutMs)));
        result.setResultMessage(message);
        return result;
    } catch (Exception ex) {
        LOG.error("Exception when performing the REST Call. " + ex.toString(), ex);
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
        message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Error on CallREST : " + ex.toString()));
        result.setResultMessage(message);
        return result;
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            LOG.error(ex.toString());
        }
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpDelete(org.apache.http.client.methods.HttpDelete) MessageEvent(org.cerberus.engine.entity.MessageEvent) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) AppServiceContent(org.cerberus.crud.entity.AppServiceContent) IFactoryAppServiceHeader(org.cerberus.crud.factory.IFactoryAppServiceHeader) AppServiceHeader(org.cerberus.crud.entity.AppServiceHeader) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpHost(org.apache.http.HttpHost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) AnswerItem(org.cerberus.util.answer.AnswerItem) ClientProtocolException(org.apache.http.client.ClientProtocolException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) InputStreamEntity(org.apache.http.entity.InputStreamEntity) SocketTimeoutException(java.net.SocketTimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) AuthScope(org.apache.http.auth.AuthScope)

Example 5 with ProxyAuthenticationStrategy

use of org.apache.http.impl.client.ProxyAuthenticationStrategy 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

HttpHost (org.apache.http.HttpHost)5 AuthScope (org.apache.http.auth.AuthScope)5 CredentialsProvider (org.apache.http.client.CredentialsProvider)5 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)5 ProxyAuthenticationStrategy (org.apache.http.impl.client.ProxyAuthenticationStrategy)5 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)3 IOException (java.io.IOException)2 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 InetSocketAddress (java.net.InetSocketAddress)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 KeyManagementException (java.security.KeyManagementException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SecureRandom (java.security.SecureRandom)1