Apache HttpClient 4.1 - Proxy Authentication
Asked Answered
D

7

31

I've been trying to configure the user and password for proxy authentication from the configured properties while using Apaches HttpComponent's httpclient, but with no success. All examples I have found refer to methods and classes that are no longer available, such as HttpState and setProxyCredentials.

So, can anyone give me an example of how to configure the proxy credentials?

Dotation answered 5/8, 2011 at 20:10 Comment(2)
Are we talking Basic-Auth or NTLM?Dossier
@Dossier I'm taking whatever I can get. Preferably, actually, both.Dotation
D
27

For Basic-Auth it looks like this:

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
    new AuthScope("PROXY HOST", 8080),
    new UsernamePasswordCredentials("username", "password"));

HttpHost targetHost = new HttpHost("TARGET HOST", 443, "https");
HttpHost proxy = new HttpHost("PROXY HOST", 8080);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

AFAIK NTLM is not supported out of the box. But you might be able to manage that using NTCredentials and maybe overloading DefaultProxyAuthenticationHandler.

Dossier answered 7/8, 2011 at 10:24 Comment(3)
what happens if proxy settings give error or the proxy server is down,how to handle these situationsMew
Isnt targetHost variable unused / unnecessary?Annalee
How can you make sure proxy is always change ip address for one run with many iterations (Let's say 100)?Endosmosis
P
42

For anyone looking for the answer for 4.3...its fairly new and their example didn't use the new HttpClientBuilder...so this is how I implemented this in that version:

NTCredentials ntCreds = new NTCredentials(ntUsername, ntPassword,localMachineName, domainName );

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials( new AuthScope(proxyHost,proxyPort), ntCreds );
HttpClientBuilder clientBuilder = HttpClientBuilder.create();

clientBuilder.useSystemProperties();
clientBuilder.setProxy(new HttpHost(pxInfo.getProxyURL(), pxInfo.getProxyPort()));
clientBuilder.setDefaultCredentialsProvider(credsProvider);
clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

CloseableHttpClient client = clientBuilder.build();
Portrait answered 3/10, 2013 at 19:20 Comment(0)
D
27

For Basic-Auth it looks like this:

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
    new AuthScope("PROXY HOST", 8080),
    new UsernamePasswordCredentials("username", "password"));

HttpHost targetHost = new HttpHost("TARGET HOST", 443, "https");
HttpHost proxy = new HttpHost("PROXY HOST", 8080);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

AFAIK NTLM is not supported out of the box. But you might be able to manage that using NTCredentials and maybe overloading DefaultProxyAuthenticationHandler.

Dossier answered 7/8, 2011 at 10:24 Comment(3)
what happens if proxy settings give error or the proxy server is down,how to handle these situationsMew
Isnt targetHost variable unused / unnecessary?Annalee
How can you make sure proxy is always change ip address for one run with many iterations (Let's say 100)?Endosmosis
F
19

Instead of NTLM one can use just plain old username and password on 4.3+ httpClient, as follows:

HttpHost proxy = new HttpHost("x.x.com",8080);
Credentials credentials = new UsernamePasswordCredentials("username","password");
AuthScope authScope = new AuthScope("x.x.com", 8080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);
HttpClient client = HttpClientBuilder.create().setProxy(proxy).setDefaultCredentialsProvider(credsProvider).build();
HttpResponse response=client.execute(new HttpGet("https://mcmap.net/q/459224/-apache-httpclient-4-1-proxy-authentication"));
Foucquet answered 1/12, 2014 at 13:58 Comment(1)
If I try and use UsernamePasswordCredentials for a proxy that requres NTLM authentication, I get the following exception: auth.HttpAuthenticator ( HttpAuthenticator.java:207) - NTLM authentication error: Credentials cannot be used for NTLM authentication: org.apache.http.auth.UsernamePasswordCredentials. To solve this I used NTCredentials insteadDrake
L
10

How to setup proxy authentication using Apache's httpclient

(Pre-authorization on proxy networks)

This answer uses Apache's HttpClient v4.1 and later.

The accepted answer didn't work for me, but I found something else that did!

Here's some tested, verified code from apache that demonstrates how to authenticate through a proxy for a HTTP request.

The full documentation is located here: https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html .

There's also an excellent example from Apache here: https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientProxyAuthentication.java

  • Replace my_username with your proxy username
  • Replace my_password with your proxy password
  • Replace proxy.mycompany.com with your proxy host
  • Replace 8080 with your proxy port
  • Replace google.com with the host of the site that you want to send your HTTP request to.
  • Replace /some-path with the path that you want to send the HTTP request to. This uses the host site you specified earlier (google.com).

The following example will authenticate username:[email protected]:8080 and send a GET request to http://www.google.com/some-path and will print the response HTTP code.

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope("proxy.mycompany", 8080),
            new UsernamePasswordCredentials("my_username", "my_password"));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
    try {
        //Replace "google.com" with the target host you want to send the request to
        HttpHost target = new HttpHost("google.com", 80, "http");
        HttpHost proxy = new HttpHost("proxy.mycompany", 8080);

        RequestConfig config = RequestConfig.custom()
            .setProxy(proxy)
            .build();
        CloseableHttpResponse response = null;

        //Replace "/some-path" with the path you want to send a get request to.
        HttpPost httppost = new HttpPost("/some-path");
        httppost.setConfig(config);
        response = httpclient.execute(target, httppost);

        try {
            System.out.println("Return status code is "+response.getStatusLine().getStatusCode());          
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
Lejeune answered 6/9, 2016 at 22:42 Comment(2)
What version of HttpClient? That is an important element, as the things I had seen for previous versions didn't work with 4.1, and one can see from answers for 4.3 and 4.5 that things changed since too.Dotation
HttpClients only exists since 4.3Rotow
W
0

A simpler thing worked for me for NTLM:

httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxy_host, proxy_port), 
                    new NTCredentials(this.proxy_user, this.proxy_pass, this.proxy_host, this.proxy_domain));
HttpHost proxy = new HttpHost(this.proxy_host, this.proxy_port, "http");
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Waterage answered 27/8, 2014 at 7:9 Comment(0)
L
0

For HttpClient 4.5 and per request authentication:

HttpContext httpContext = new BasicHttpContext();
AuthState authState = new AuthState();

authState.update(new BasicScheme(), new UsernamePasswordCredentials("userName", "password"));
httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);
Longheaded answered 16/10, 2015 at 11:58 Comment(1)
how does this work if you are not setting the proxy host/port?Briny
F
0

If you have to keep your code working with 4.1 or want to use the below snippet, it's important to know that httpclient 4.1 will not send the authentication to proxy. You will probably get a 407 "Proxy Authentication Required" status code. I upgraded to 4.3.3 and all worked well, although DefaultHttpClient and ConnRoutePNames were deprecated in this release. Hope this helps!

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
    new AuthScope("PROXY HOST", 8080),
    new UsernamePasswordCredentials("username", "password"));

HttpHost proxy = new HttpHost("PROXY HOST", 8080);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Flyaway answered 19/8, 2019 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.