Auth proxy with JAVA

In the post we’ll show how to leverage auth ptoxy (with login/pass) for JAVA application.

The following code defines Authenticator class that thru the static method setDefault sets authentication for a network connection.


// the `dk.http.auth.tunneling.disabledSchemes` property contains the authentication schemes 
// that will be disabled when tunneling HTTPS over a proxy with the HTTP CONNECT method
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

String host = "<host>";
String port = "<port>";
String user = "<login>";
String password = "<pass>";

System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port);
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port);

// The class `Authenticator` represents an object that knows how to obtain authentication for a network connection
  new Authenticator() {
    // The method `getPasswordAuthentication` is called when password authorization is needed. 
    // Subclasses should override the default implementation, which returns `null`
    public PasswordAuthentication getPasswordAuthentication() {
      if (getRequestorType() == RequestorType.PROXY)
            return new PasswordAuthentication(user, password.toCharArray());
        return super.getPasswordAuthentication();

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.