Java proxy authentication
I have a Java webapp running in Tomcat 6 that loads RSS feeds from remote URLs
I use Rome to handle RSS feeds and different formats for me The connecting part looks like this:
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...}
The code works normally, except in this new client, they use a proxy
In order to use the proxy, I set up http Proxyhost and proxyport system properties:
System.setProperty("http.proxyHost",proxyHost); System.setProperty("http.proxyPort",proxyPort); System.setProperty("https.proxyHost",proxyHost); System.setProperty("https.proxyPort",proxyPort);
HTTP get proxy is good, but now I receive an HTTP 502 error (bad gateway or something like that)
Analyzing the HTTP exchange with Wireshark, I noticed that the proxy needs authentication It sends HTTP 507 Java tried to authenticate in some way, but it used the wrong user name and password It seems that the host name is used as the user name for the password I don't know
So I try to implement the authenticator method to specify the user name and password:
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()); } });
Now my problem is that it is ignored The getpasswordauthentication method will never be called I don't see logging statements in the log file and use Wireshark. I can see that it still uses the hostname as the user name
Why? It seems that Java somehow tried to authenticate itself without consulting the authenticator
The agent appears to be an MS device that uses NTLM for authentication Is there any built-in mechanism in Java to deal with this problem? The machine on which the application runs is win Server 2008 R2
Solution
Here we do the same for NTLM - based proxy authentication
Authentication on the proxy is actually ordinary HTTP basic authentication
We use the following methods:
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; }
This completes this trick with the proxy JVM setup
see http://en.wikipedia.org/wiki/Basic_access_authentication.