Allan Lykke Christensen Allan Lykke Christensen - 1 month ago 13x
Java Question

JCIFS NTLM Authentication for HTTP Connections on GlassFish (or any servlet container)

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.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) {

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
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.


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() {
        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();

    StringBuilder response = new StringBuilder();
    InputStream stream = conn.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
    String str = "";
    while ((str = in.readLine()) != null) {

    return response.toString();