your programing

Java로 인증 된 HTTP 프록시

lovepro 2020. 12. 26. 16:17
반응형

Java로 인증 된 HTTP 프록시


Java를 사용하여 http 프록시 서버를 인증하기 위해 사용자 이름과 비밀번호를 구성하려면 어떻게해야합니까?

방금 다음 구성 매개 변수를 찾았습니다.

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

하지만 내 프록시 서버에는 인증이 필요합니다. 프록시 서버를 사용하도록 내 앱을 구성하려면 어떻게해야합니까?


(편집 : OP에서 지적했듯이 a를 사용하는 java.net.Authenticator것도 필요합니다. 정확성을 위해 그에 따라 내 대답을 업데이트하고 있습니다.)

인증의 경우 java.net.Authenticator프록시 구성을 설정하고 시스템 속성 http.proxyUserhttp.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);

거의 완료되었습니다. 다음을 추가하기 만하면됩니다.

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

http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword 말한다 :

다른 사용자는 사용자 정의 기본 인증기를 사용하는 것이 좋습니다. 그러나 이것은 묻는 사람에게 암호를 보낼 수 있기 때문에 위험합니다.

이는 일부 http / https 요청이 프록시를 통과하지 않는 경우 관련됩니다 (구성에 따라 가능). 이 경우 자격 증명을 프록시가 아닌 일부 http 서버로 직접 보냅니다.

그는 다음 수정을 제안합니다.

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

나는 아직 시도하지 않았지만 나에게는 좋아 보인다.

이 때문에 equals (host.toLowerCase ()) 대신 equalsIgnoreCase ()를 사용하기 위해 원본 버전을 약간 수정했습니다. http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug 및 I Integer.parseInt (port)에서 NumberFormatException을 방지하기 위해 포트의 기본값으로 "80"을 추가했습니다.


대부분의 답변은 기존 답변에 있지만 저에게는 그렇지 않습니다. 이것은 java.net.HttpURLConnection에서 저에게 효과적입니다 (JDK 7 및 JDK 8로 모든 경우를 테스트했습니다). Authenticator 클래스를 사용할 필요가 없습니다.

사례 1 : 사용자 인증이없는 프록시, HTTP 리소스에 액세스

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

사례 2 : 사용자 인증을 사용하는 프록시, HTTP 리소스에 액세스

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

사례 3 : 사용자 인증이없는 프록시, HTTPS 리소스 (SSL)에 액세스

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

사례 4 : 사용자 인증을 사용하는 프록시, HTTPS 리소스 (SSL)에 액세스

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

사례 5 : 사용자 인증이없는 프록시, HTTP 및 HTTPS 리소스 (SSL) 모두에 액세스

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

사례 6 : 사용자 인증을 사용하는 프록시, HTTP 및 HTTPS 리소스 (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

System.setProperty ( "key", "value)로 속성을 설정할 수도 있습니다.

HTTPS 리소스에 액세스하려면 서버 인증서를 다운로드하고 신뢰 저장소에 저장 한 다음 해당 신뢰 저장소를 사용하여 리소스를 신뢰해야 할 수 있습니다.

 System.setProperty("javax.net.ssl.trustStore", "c:/temp/cert-factory/my-cacerts");
 System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

그러나 해당 매개 변수 만 설정하면 인증이 작동하지 않습니다.

해당 코드에 다음을 추가해야합니다.

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

Java 1.8 이상의 경우 다음을 설정해야합니다.

-Djdk.http.auth.tunneling.disabledSchemes =

수락 된 답변에 언급 된대로 Authenticator와 함께 https와 함께 작동하는 Basic Authorization으로 프록시를 만드는 방법


내가 쓴이 러너를 사용해보세요. 도움이 될 수 있습니다.

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

}

참조 URL : https://stackoverflow.com/questions/1626549/authenticated-http-proxy-with-java

반응형