【问题标题】:Java Proxy AuthenticationJava 代理身份验证
【发布时间】:2023-03-25 08:46:01
【问题描述】:

我有一个在 Tomcat 6 中运行的 Java webapp,它从远程 URL 加载 RSS 提要。

我使用Rome 为我处理 RSS 提要和不同的格式。连接部分如下所示:

try{
  feedSource = new URL(rssObject.getAsset());
}catch(MalformedURLException mue){
  logger.error(...);
  throw mue;
}

try{
    URLConnection connection = feedSource.openConnection();
    feed = new SyndFeedInput().build(new XmlReader(connection));
}catch(Exception){handle...}

代码运行良好,但在这个使用代理的新客户端除外。

为了使用代理,我设置了 http.proxyHost 和 proxyPort 系统属性:

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

对代理进行了 HTTP GET,但现在我收到 HTTP 502 错误(网关错误或类似的东西)。

分析与 Wireshark 的 HTTP 交换,我注意到代理需要身份验证。它发送一个 HTTP 507。Java 以某种方式尝试进行身份验证,但它使用了错误的用户名和密码。好像是用主机名作为用户名,至于密码我不知道。

所以我尝试实现指定用户名+密码的Authenticator方法:

Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password));
                return new PasswordAuthentication(username, password.toCharArray());
            }
        });

现在我的问题是它被忽略了。永远不会调用 getPasswordAuthentication 方法。我在日志文件中没有看到日志记录语句,使用 Wireshark 可以看到它仍然使用主机名作为用户名。

为什么?似乎 java 在不咨询 Authenticator 的情况下以某种方式尝试自行进行身份验证。

代理似乎是使用 NTLM 进行身份验证的 MS 设备。 java中是否有一些内置机制来处理这个问题?运行应用的机器是 Win Server 2008 R2。

【问题讨论】:

    标签: java authentication networking proxy


    【解决方案1】:

    我们在基于 NTLM 的代理上进行了相同的身份验证。

    proxy上的认证其实就是普通的HTTP Basic Authentication

    我们使用了以下方法:

    protected URLConnection newURLConnection(URL pURL) throws IOException {
        URLConnection urlConnection = super.newURLConnection(pURL);
    
        String auth = new String(Base64.base64Encode(new String("username:password").getBytes()));
        auth = "Basic " + auth;
        urlConnection.setRequestProperty("Proxy-Connection","Keep-Alive");
        urlConnection.setRequestProperty("Proxy-Authorization",auth);
        return urlConnection;
    }
    

    这与代理 jvm 设置一起成功了。

    http://en.wikipedia.org/wiki/Basic_access_authentication

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2020-12-07
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多