Categories
Coding

NTLM Proxy Authentication and Jakarta HttpClient

How to authenticate against an NTLM-based proxy server using Jakarta HttpClient.

In my current work environment, our Web access is proxied via a MS ISA server, which uses NTML proxy authentication. I was recently looking at NTLM proxy authentication, as I had problems running Subversion inside the proxy (this should be fixed now with the newest release of Neon, Subversion’s WebDAV layer). I am currently looking at some NTLM providers in the Java space, and one of the obvious ones I came across is the Jakarta HttpClient. Here is an example that will authenticate to an NTLM-based proxy. The code is for HttpClient 3.0-RC2.


package uk.co.researchkitchen.ntlm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class TestNTLM {

    private void execute() throws HttpException, IOException {
        HttpClient proxyclient = new HttpClient();

        proxyclient.getHostConfiguration().setHost("www.yahoo.com");
        proxyclient.getHostConfiguration().setProxy("lproxyhost.researchkitchen.co.uk"8080);


        List authPrefs = new ArrayList();
        authPrefs.add(AuthPolicy.NTLM);

        proxyclient.getState().setProxyCredentials(
            new AuthScope(null, 8080null),
            new NTCredentials("username""password""""MYDOMAIN"));

        proxyclient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

        GetMethod get = new GetMethod("/");
        int status = proxyclient.executeMethod(get);

        System.out.println(status);

        BufferedReader bis = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));

        int count = 0;
        int read = 0;
        System.out.println("Content length: " + get.getResponseContentLength());
        char[] body = new char[2048];
        do {
          count = bis.read(body);
          read += count;
          System.out.println(body);
        while (count != -1);

        System.out.println("Read " + read + " bytes");
    }


    public static void main(String[] argsthrows HttpException, IOException {
        new TestNTLM().execute();
    }

}

Leave a Reply