Categories
Development

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.

import java.net.Authenticator;
import java.net.PasswordAuthentication;

...
// 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
Authenticator.setDefault(
  new Authenticator() {
    @Override
    // 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. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

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