Tuesday, June 24, 2008

NTLM Authentication from Java

Connecting to a web page from Java is very easy. You use the HttpURLConnection method like so:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();


This works, but what if you need to access a password protected web page? Then you need to define an "Authenticator."
static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("trying to authenticate");
return new PasswordAuthentication("username", "password".toCharArray());
}
}


Now before you call HttpUrlConnection you set the authenticator. The full code is displayed below:


import java.io.*;
import java.net.*;
class Notify {
static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("trying to authenticate");
return new PasswordAuthentication("username", "password".toCharArray());
}
}
public static void main(String argv[]) throws Exception {
// Construct data
Authenticator.setDefault(new MyAuthenticator());
URL url = new URL("<ntlm protected="" url="">");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();

}
}


Hope that helps...

5 comments:

Dilip Kumar said...

Thank U very much.

picture said...

Please Help me to connect to an URL with NTLMv2 based authentication.
Thanks in Advance.

developer-resource said...

Picture: Unfortunately I know of no standard library that supports NTLMv2 due to licensing concerns.

If you find something please post back as I would love to have that information. Thankfully at my work the Windows folks are willing to let me connect through NTLM on our intranet which avoids this problem.

VittyO said...
This comment has been removed by the author.
VittyO said...

JDK 5 HttpURLConnection introduced full support for NTLM v2 authentication. It's built-in and handles all of the HTTP 401 negotiation challenges.