72

How can I configure the username and password to authenticate a http proxy server using Java?

I just found the following configuration parameters:

http.proxyHost=<proxyAddress>
http.proxyPort=<proxyPort>
https.proxyHost=<proxyAddress>
https.proxyPort=<proxyPort>

But, my proxy server requires authentication. How can I configure my app to use the proxy server?

1
  • 2
    What kind of authentication does your proxy server accept/require? Basic, Digest, or NTLM?
    – brianegge
    Oct 27, 2009 at 1:56

8 Answers 8

92

(EDIT: As pointed out by the OP, the using a java.net.Authenticator is required too. I'm updating my answer accordingly for the sake of correctness.)

(EDIT#2: As pointed out in another answer, in JDK 8 it's required to remove basic auth scheme from jdk.http.auth.tunneling.disabledSchemes property)

For authentication, use java.net.Authenticator to set proxy's configuration and set the system properties http.proxyUser and http.proxyPassword.

final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
  new Authenticator() {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(authUser, authPassword.toCharArray());
    }
  }
);

System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
5
  • 2
    I too got the response with the code snippet. But when I set the wrong values for password, if the request went through the proxy, it should say Connection refused. I got the output in that case as well. How can I verify if the requests are being sent via the proxy??? Jan 30, 2013 at 13:11
  • 2
    @Pascal: I think you meant those last 2 lines to set proxyHost and proxyPort, not proxyUser and proxyPassword, as the latter are already established by the Authenticator. Or am I missing something? Aug 26, 2013 at 12:40
  • @divinedragon It shouldn't say 'connection refused'. It's not even possible. The connection was accepted by TCP, to the proxy, which then failed your authentication. At that point it is impossible for the proxy to generate a connection refusal.
    – user207421
    Apr 26, 2014 at 10:38
  • 4
    The properties "http.proxyUser" and "http.proxyPassword" are not obligatory. You're specifying the Authenticator for the JVM. So, you can remove those configurations.
    – R. Karlus
    Aug 8, 2017 at 17:59
  • Isn't it better to create the PasswordAuthentication outside of the anonymous class and return it in getPasswordAuthentication, this will prevent creating a new object each time the proxy authentication is required. Jan 23, 2020 at 15:22
43

You're almost there, you just have to append:

-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword
34

http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:

Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.

This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.

He suggests the following fix.

// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            String prot = getRequestingProtocol().toLowerCase();
            String host = System.getProperty(prot + ".proxyHost", "");
            String port = System.getProperty(prot + ".proxyPort", "80");
            String user = System.getProperty(prot + ".proxyUser", "");
            String password = System.getProperty(prot + ".proxyPassword", "");

            if (getRequestingHost().equalsIgnoreCase(host)) {
                if (Integer.parseInt(port) == getRequestingPort()) {
                    // Seems to be OK.
                    return new PasswordAuthentication(user, password.toCharArray());  
                }
            }
        }
        return null;
    }  
});

I haven't tried it yet, but it looks good to me.

I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).

31

Most of the answer is in existing replies, but for me not quite. This is what works for me with java.net.HttpURLConnection (I have tested all the cases with JDK 7 and JDK 8). Note that you do not have to use the Authenticator class.

Case 1 : Proxy without user authentication, access HTTP resources

-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=myport

Case 2 : Proxy with user authentication, access HTTP resources

-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=myport -Dhttps.proxyUser=myuser -Dhttps.proxyPassword=mypass

Case 3 : Proxy without user authentication, access HTTPS resources (SSL)

-Dhttps.proxyHost=myproxy -Dhttps.proxyPort=myport 

Case 4 : Proxy with user authentication, access HTTPS resources (SSL)

-Dhttps.proxyHost=myproxy -Dhttps.proxyPort=myport -Dhttps.proxyUser=myuser -Dhttps.proxyPassword=mypass

Case 5 : Proxy without user authentication, access both HTTP and HTTPS resources (SSL)

-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=myport -Dhttps.proxyHost=myproxy -Dhttps.proxyPort=myport 

Case 6 : Proxy with user authentication, access both HTTP and HTTPS resources (SSL)

-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=myport -Dhttp.proxyUser=myuser -Dhttp.proxyPassword=mypass -Dhttps.proxyHost=myproxy -Dhttps.proxyPort=myport -Dhttps.proxyUser=myuser -Dhttps.proxyPassword=mypass

You can set the properties in the with System.setProperty("key", "value) too.

To access HTTPS resource you may have to trust the resource by downloading the server certificate and saving it in a trust store and then using that trust store. ie

 System.setProperty("javax.net.ssl.trustStore", "c:/temp/cert-factory/my-cacerts");
 System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
4
  • 1
    I can confirm that using the Authenticator class is not required on JDK 7 or 8. Just use -D<proto>.proxyUser= and -D<proto>.proxyPassword=. Mar 29, 2017 at 16:56
  • 1
    For 2019 (JDK7+) this is the correct answer. The only thing missing to be totally complete is the no-proxy settings: To bypass your proxy for certain domains use -Dhttp.nonProxyHosts=*.mydomain.com|localhost. Note, that this setting is used for both HTTP and HTTPS. More info at the official documentation Jun 7, 2019 at 5:48
  • 2
    It doesn't work on linux using oracle jdk 'ava version "1.8.0_231"' or "java version "11.0.5" 2019-10-15 LTS" Downvoted as I suppose that something else is happening during the reported working tests. (is it something windows specific?)
    – jonenst
    Apr 29, 2020 at 11:38
  • 1
    This answer made me realize something obvious but that I wasn't seeing, nor was finding in other answers: http.proxyHost and https.proxyHost are different things!!! setting a "HTTP proxy" does not work with a "HTTPS URL call"
    – res
    Jun 10, 2022 at 9:12
17

For Java 1.8 and higher you must set

-Djdk.http.auth.tunneling.disabledSchemes=

to make proxies with Basic Authorization working with https along with Authenticator as mentioned in accepted answer

1
  • 4
    And the schemes must be empty?
    – Lonzak
    Jul 26, 2019 at 6:57
13

But, setting only that parameters, the authentication don't works.

Are necessary to add to that code the following:

final String authUser = "myuser";
final String authPassword = "secret";

System.setProperty("http.proxyHost", "hostAddress");
System.setProperty("http.proxyPort", "portNumber");
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

Authenticator.setDefault(
  new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(authUser, authPassword.toCharArray());
    }
  }
);
2
  • 1
    You do not have to add the Authenticator. For me, with Java 7 and Java 8 it enough to set the http.* properties. Dec 6, 2016 at 13:31
  • Correct, the basic authentication is introduced after java8_111 by default installation. In this case, the Authenticator is needed.
    – dimeros
    Dec 9, 2020 at 23:53
5

Try this runner I wrote. It could be helpful.

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

public class ProxyAuthHelper {

    public static void main(String[] args) throws Exception {
        String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
        if (tmp == null) {
            System.out.println("Proxy username: ");
            tmp = new Scanner(System.in).nextLine();
        }
        final String userName = tmp;

        tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
        if (tmp == null) {
            System.out.println("Proxy password: ");
            tmp = new Scanner(System.in).nextLine();
        }
        final char[] password = tmp.toCharArray();

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                System.out.println("\n--------------\nProxy auth: " + userName);
                return new PasswordAuthentication (userName, password);
            }

         });

        Class<?> clazz = Class.forName(args[0]);
        Method method = clazz.getMethod("main", String[].class);
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, newArgs.length);
        method.invoke(null, new Object[]{newArgs});
    }

}
1
  • I faced with this exception: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at md.ProxyAuthHelper.main(ProxyAuthHelper.java:42)
    – MrSalesi
    Jul 9 at 9:11
2

Since no one has mentioned this and I have seen a few examples where Authenticator.setDefault, this can cause unintentionally leaking of your username and password. Here is another way of doing this, I think this is much cleaner.

import java.net.*;
import java.util.Base64;

class JavaFileUtil {
  private String hostname = "hostname";
  private int port = 8000;
  private String username = "username";
  private String password = "password";

  private Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port));
  private String authHeader = new String(Base64.getEncoder().encode(new String(username + ":" + password).getBytes()));

  public void download(URL url) {
    HttpURLConnection newConnection = null;
    try {
      newConnection = (HttpURLConnection) url.openConnection(proxy);
      newConnection.setRequestProperty("Proxy-Authorization", "Basic " + authHeader);

      //The rest of your code here

    } catch (Exception e) {
      //log some error or handle it
    } finally {
      //Make sure you close the connection
      if (newConnection != null) newConnection.disconnect();
    }
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.