Thursday, May 27, 2010

Proxy Authentication from a Java Code

People who are behind company/campus proxies especially those requiring authentication must have faced this problem many times. Say, you are using an API call which does some resource fetching from outside the proxy for you. Now, you need to tell the API that, look, this is the proxy, this is the port and this is the username and password for you to pass through it. Typically, you would try doing this by setting system properties like http.proxyHost, http.proxyPort, http.proxyUser and http.proxyPass respectively. However, turns out that this may not help in some unfortunate cases like mine.. :-)

Some background: I was working on a code which was using an API call to a function (it was actually an application based on the OWLS to UDDI matchmaker client API) which did some ontology accessing using Jena. I needed my code to be able to refer to the ontologies outside seemlessly.

I set all those system properties, changed them to see if it works. But it didn't. It continuously gave me the http 407 response code (proxy authentication reqd).

Now, there are 2 ways in which you can solve such a problem:
1. Creating a proxy authenticator class
2. Setting up a local proxy for the remote proxy.


1. Creating a proxy authenticator class:

I must say this is a rather non-trivial solution. One cannot possibly think of this unless told. Thanks to my friend Nishant who showed me how he had used this in one of his programs and the chap here who has posted this solution.

(a) Create a separate class in the project, say, ProxyAuthenticator:

import java.net.*;

class ProxyAuthenticator extends Authenticator {

private String user, password;

public ProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}

}

(b) Then, create an object of this class in the code just before the call that accesses outside data:

Authenticator.setDefault(new ProxyAuthenticator("MyUsername", "MyPassword"));

Also set the proxy username and password through system properties:

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


2. Setting up a local proxy for the remote proxy:

A local proxy is a program that will basically do all remote proxy authentication for requests going out of your machine.
So, you make calls from your machine as if there was no proxy. These calls pass through the local proxy which does the remote proxy authentication for you.

Squid is one such proxy that you can set up. A very good guide to setting up squid can be found on my friend Prashant Borole's blog here. Don't forget to read the notes of caution given by him at the end.

Happy Coding!
Dhaval

No comments: