Skip to main content

problems using HTTPUrlConnection with ntlm protected resource

No replies
bobzee
Offline
Joined: 2010-01-20
Points: 0

Hi,

I have been struggling with this for a few days, searched google, followed various examples but have been unable to get it working ...

I am trying to access a webservice that is protected by NTLM v1 from a a java client. The java client is running on a windows PC that is logged in to the same domain as the server ..and the logged in user has correct permissions to access the webservice. I have trimmed it down to writing a simple test to perform a get on a resource and that is still not working...note I can access the resource from a browser no problem..

I am using Java 1.6

Here is my code:

public class JavaHTTPTEST {

static final String kuser = "myuser"; // your account name
static final String kpass = "mypass"; // your password for the account

static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
// I haven't checked getRequestingScheme() here, since for NTLM
// and Negotiate, the usrname and password are all the same.
System.err.println("Feeding username and password for " + getRequestingScheme());
return (new PasswordAuthentication(kuser, kpass.toCharArray()));
}
}

public static void main(String[] args) throws Exception {
Authenticator.setDefault(new MyAuthenticator());
System.setProperty("http.auth.ntlm.domain","mydomain");
URL url = new URL("http://myserver/sharepointusersdoclibrary/Forms/AllItems.aspx");

URLConnection connection = url.openConnection();

InputStream ins = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
String str;
while((str = reader.readLine()) != null)
System.out.println(str);
}
}

The output is:
Feeding username and password for ntlm
Exception in thread "main" java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at JavaHTTPTEST.main(JavaHTTPTEST.java:33)

This fail with a 401 unauthorized error returned from the server. I have monitored the traffic using Wireshark and can see the ntlm negotiation and it seems fine.(i.e. the negotiation happens and the user name domain and password are included in the header) I have written a .net test program that does exactly the same thing and it works fine from the same machine, and I have written another test program that uses a commercial java HTTP library and it works fine..

However as I understand it this should work using Java 1.6, and in fact I should be able to support NTLM v2 also.

I would be grateful if anybody had any suggestions.

Thanks