org.apache.http.impl.client.ProxyAuthenticationStrategy Java Examples

The following examples show how to use org.apache.http.impl.client.ProxyAuthenticationStrategy. 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: HttpClientConfigurer.java    From spring-cloud-dataflow with Apache License 2.0 7 votes vote down vote up
/**
 * Configures the {@link HttpClientBuilder} with a proxy host. If the
 * {@code proxyUsername} and {@code proxyPassword} are not {@code null}
 * then a {@link CredentialsProvider} is also configured for the proxy host.
 *
 * @param proxyUri Must not be null and must be configured with a scheme (http or https).
 * @param proxyUsername May be null
 * @param proxyPassword May be null
 * @return a reference to {@code this} to enable chained method invocation
 */
public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) {

	Assert.notNull(proxyUri, "The proxyUri must not be null.");
	Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty.");

	httpClientBuilder
		.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
	if (proxyUsername !=null && proxyPassword != null) {
		final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
		credentialsProvider.setCredentials(
			new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
			new UsernamePasswordCredentials(proxyUsername, proxyPassword));
		httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
			.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
	}
	return this;
}
 
Example #2
Source File: PGPKeysServerClient.java    From pgpverify-maven-plugin with Apache License 2.0 7 votes vote down vote up
protected HttpClientBuilder setupProxy(HttpClientBuilder clientBuilder) {
    if (this.proxy == null) {
        return clientBuilder;
    }

    if (proxy.getUsername() != null && !proxy.getUsername().isEmpty() &&
        proxy.getPassword() != null && !proxy.getPassword().isEmpty()) {
        clientBuilder.setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE);
        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        AuthScope proxyAuthScope = new AuthScope(proxy.getHost(), proxy.getPort());
        UsernamePasswordCredentials proxyAuthentication =
            new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
        basicCredentialsProvider.setCredentials(proxyAuthScope, proxyAuthentication);
        clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
    }
    return clientBuilder;
}
 
Example #3
Source File: HttpBuilderConfigurationTest.java    From FcmJava with MIT License 5 votes vote down vote up
@Test
public void testFcmClientWithProxySettings() throws Exception {

    // Create Settings:
    IFcmClientSettings settings = new FakeFcmClientSettings();

    // Define the Credentials to be used:
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();

    // Set the Credentials (any auth scope used):
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("your_username", "your_password"));

    // Create the Apache HttpClientBuilder:
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            // Set the Proxy Address:
            .setProxy(new HttpHost("your_hostname", 1234))
            // Set the Authentication Strategy:
            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
            // Set the Credentials Provider we built above:
            .setDefaultCredentialsProvider(basicCredentialsProvider);

    // Create the DefaultHttpClient:
    DefaultHttpClient httpClient = new DefaultHttpClient(settings, httpClientBuilder);

    // Finally build the FcmClient:
    try(IFcmClient client = new FcmClient(settings, httpClient)) {
        // TODO Work with the Proxy ...
    }
}
 
Example #4
Source File: ProxyService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpClientBuilder getBuilderWithProxy(String system, String url) {
    try {

        if (useProxy(url, system)) {

            String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
            int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);

            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);

                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));

                LOG.debug("Activating Proxy With Authentification.");
                return HttpClientBuilder.create().setProxy(proxyHostObject)
                        .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
                        .setDefaultCredentialsProvider(credsProvider);

            } else {

                LOG.debug("Activating Proxy (No Authentification).");
                return HttpClientBuilder.create().setProxy(proxyHostObject);
            }
        } else {
            return HttpClientBuilder.create();
        }

    } catch (Exception e) {
        LOG.error("Exception when building httpClientBuilder.", e);
    }
    return HttpClientBuilder.create();
}
 
Example #5
Source File: HttpClientAdapter.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initialize an {@link HttpClient} for performing requests. Proxy settings will
 * be read from the configuration and applied transparently.
 */
public HttpClientAdapter() {
    Optional<SSLConnectionSocketFactory> sslSocketFactory = Optional.empty();
    try {
        SSLContext sslContext = SSLContext.getDefault();
        sslSocketFactory = Optional.of(new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"},
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()));
    }
    catch (NoSuchAlgorithmException e) {
        log.warn("No such algorithm. Using default context", e);
    }

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    sslSocketFactory.ifPresent(sf -> clientBuilder.setSSLSocketFactory(sf));

    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    Builder requestConfigBuilder = RequestConfig.custom()
            .setConnectTimeout(Config.get().getInt(HTTP_CONNECTION_TIMEOUT, 5) * TO_MILLISECONDS)
            .setSocketTimeout(Config.get().getInt(HTTP_SOCKET_TIMEOUT, 5 * 60) * TO_MILLISECONDS)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES);

    // Store the proxy settings
    String proxyHostname = ConfigDefaults.get().getProxyHost();
    if (!StringUtils.isBlank(proxyHostname)) {
        int proxyPort = ConfigDefaults.get().getProxyPort();

        proxyHost = new HttpHost(proxyHostname, proxyPort);
        clientBuilder.setProxy(proxyHost);

        String proxyUsername = ConfigDefaults.get().getProxyUsername();
        String proxyPassword = ConfigDefaults.get().getProxyPassword();
        if (!StringUtils.isBlank(proxyUsername) &&
                !StringUtils.isBlank(proxyPassword)) {
            Credentials proxyCredentials = new UsernamePasswordCredentials(
                    proxyUsername, proxyPassword);

            credentialsProvider.setCredentials(new AuthScope(proxyHostname, proxyPort),
                    proxyCredentials);
        }

        // Explicitly exclude the NTLM authentication scheme
        requestConfigBuilder =  requestConfigBuilder.setProxyPreferredAuthSchemes(
                                Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC));

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        clientBuilder.setRoutePlanner(new CustomProxyRoutePlanner(proxyHost));
    }

    // Read proxy exceptions from the "no_proxy" config option
    String noProxy = Config.get().getString(NO_PROXY);
    if (!StringUtils.isBlank(noProxy)) {
        for (String domain : Arrays.asList(noProxy.split(","))) {
            noProxyDomains.add(domain.toLowerCase().trim());
        }
    }

    requestConfig = requestConfigBuilder.build();
    clientBuilder.setMaxConnPerRoute(Config.get().getInt(MAX_CONNCECTIONS, 1));
    clientBuilder.setMaxConnTotal(Config.get().getInt(MAX_CONNCECTIONS, 1));
    httpClient = clientBuilder.build();
}
 
Example #6
Source File: SlackService.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void sendSlackMessage(JSONObject cerberusMessage, String webHook) throws Exception {

    CloseableHttpClient httpclient = null;
    HttpClientBuilder httpclientBuilder;

    if (proxyService.useProxy(webHook, "")) {

        String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", "", DEFAULT_PROXY_HOST);
        int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", "", DEFAULT_PROXY_PORT);

        HttpHost proxyHostObject = new HttpHost(proxyHost, proxyPort);

        if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", "", DEFAULT_PROXYAUTHENT_ACTIVATE)) {

            String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", "", DEFAULT_PROXYAUTHENT_USER);
            String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", "", DEFAULT_PROXYAUTHENT_PASSWORD);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));

            LOG.debug("Activating Proxy With Authentification.");
            httpclientBuilder = HttpClientBuilder.create().setProxy(proxyHostObject)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
                    .setDefaultCredentialsProvider(credsProvider);

        } else {

            LOG.debug("Activating Proxy (No Authentification).");
            httpclientBuilder = HttpClientBuilder.create().setProxy(proxyHostObject);
        }
    } else {
        httpclientBuilder = HttpClientBuilder.create();
    }

    boolean acceptUnsignedSsl = parameterService.getParameterBooleanByKey("cerberus_accept_unsigned_ssl_certificate", "", true);

    if (acceptUnsignedSsl) {
        // authorize non valide certificat ssl
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();

        httpclientBuilder
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }

    httpclient = httpclientBuilder.build();

    HttpPost post = new HttpPost(webHook);
    List<NameValuePair> nvps = new ArrayList<>(1);
    nvps.add(new BasicNameValuePair("payload", cerberusMessage.toString()));

    post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

    HttpResponse response = httpclient.execute(post);

    int rc = response.getStatusLine().getStatusCode();
    LOG.debug("Slack request http return code : " + rc);

}