11.11. NTLM Authentication

Problem

You need to access a resource that is protected by Microsoft’s NTLM authentication protocol.

Solution

Create an instance of NTCredentials with a username, password, host, and domain, and call setCredentials() on the HttpState associated with an instance of HttpClient. The following example demonstrates the use of NTCredentials to access a resource on host test.windowsmachine.com, which is on the domain TESTDOM:

               import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.methods.GetMethod;

HttpClient client = new HttpClient( );

// Set credentials on the client
               Credentials credentials =
               new NTCredentials( "testuser", "crazypass", 
                       "homecomputer ", "TESTDOM" );
               HttpState state = client.getState( );
               state( ).setCredentials( null, null, credentials );

String url = "http://webmail.domain.biz/exchange/";
HttpMethod method = new GetMethod( url );
    
client.executeMethod( method );
String response = method.getResponseBodyAsString( );

System.out.println( response );
method.releaseConnection( );

Discussion

The parameters to the constructor of NTCredentials are the username, the password, a hostname, and a domain. The hostname is the name of the machine making the request, and, in this case, ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.