JCIFS NTLM Authentication for HTTP Connections on GlassFish (or any servlet container)
Question
I've created a Java class that connects to an IIS website requiring NTLM authentication. The Java class uses the JCIFS library and is based on the following example:
Config.registerSmbURLHandler();
Config.setProperty("jcifs.smb.client.domain", domain);
Config.setProperty("jcifs.smb.client.username", user);
Config.setProperty("jcifs.smb.client.password", password);
URL url = new URL(location);
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
The example works fine when executed from the command prompt, but as soon as I try to use the same code in a servlet container (specifically GlassFish), I get an IOException
containing the message "Server returned HTTP response code: 401 for URL: ....".
I've tried moving the jcifs jar to the system classpath (%GLASSFISH%/lib), but that doesn't seem to make any difference.
Suggestions are highly appreciated.
Solution
It seems that what I was trying to do is already supported in Java 5/6 and I was therefore able to drop the JCIFS API and do something like this instead:
public static String getResponse(final ConnectionSettings settings,
String request) throws IOException {
String url = settings.getUrl() + "/" + request;
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println(getRequestingScheme() + " authentication")
// Remember to include the NT domain in the username
return new PasswordAuthentication(settings.getDomain() + "\\" +
settings.getUsername(), settings.getPassword().toCharArray());
}
});
URL urlRequest = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
StringBuilder response = new StringBuilder();
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
return response.toString();
}
OTHER TIPS
Sounds like JCIFS does not have the right to set a factory for handling your URLs inside Glassfish. You should check the policy settings (checkSetFactory).
The Config#registerSmbURLHandler() might swallow the SecurityException.