URL Based HTTP Authentication

I ran into a situation the other day where I needed to connect to a remote Web server from a server side application. This web server requires HTTP authentication. The user sets the Web Server location from a configuration file.

What I wanted to be able to do was have the user enter the URL in the following format:
http://user:password@server.com/somewhere

The plan was to use Java’s URL connection library to make my connection to the website. I figured that the default implementation of the URL authentication would allow the user name and password to be supplied as part of the URL. To my surprise, I was greeted with a “401 Unauthorized” message.

The way to provide HTTP based authentication in Java is using the java.net.Authenticator mechanism. Java 5 provides a new method on the Authenticator called getRequestingURL(). This allows access to the URL that requested the authentication. By using this method, an Authenticator can get access to the user name and password embedded in the URL.

So, I created a simple Authenticator that uses the Apache Commons HTTPClient to parse the URL and pull out the authentication information.

Here is the code:

public class HTTPAuthenticator extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
       if (!getRequestingProtocol().equals("http") &&
               !getRequestingProtocol().equals("https")) {
           return null;
       }       URL url = getRequestingURL();
       try {
           // Get the Username and password from the URL
           HttpURL httpUrl = new HttpURL(url.toString());
           String username = httpUrl.getUser();
           char[] password = httpUrl.getRawPassword();
           if (username == null || password == null) {
               return null;
           }
           return new PasswordAuthentication(username, password);
       }
       catch (Exception e) {
           return null;
       }
    }
    public void init() {

        Authenticator.setDefault(this);

    }
}