2

By default sending a request with RESTEasy client API to a secured resource that requires NTLM authentication results in a HTTP response with status 401 Unauthorized and header WWW-Authenticate: NTLM.

How to enable NTLM authentication with RESTEasy client API and how to provide the credentials?

There already are related questions with helpful answers:

They are somewhat outdated (using deprecated and legacy API) and have slightly different requirements.

After struggling with the task to consume an ASP.NET Web API REST service hosted on Internet Information Services (IIS) from Java using JAX-RS 2.0 compliant RESTEasy Client API, i would like to share my experiences with a roundup in an answer to this question.

irieill
  • 1,203
  • 10
  • 32

1 Answers1

3

Authentication with RESTEasy Client API is done by the encapsulated ClientHttpEngine. Version 3.0.19.Final, which i am refering to in this answer, is JAX-RS 2.0 compliant and ships with two implementations. Both can do NTLM authentication.

Using the default ApacheHttpClient4Engine

Even if it is the default engine, you need to setup a custom instance to provide the credentials. First the Credentials have to be added to a CredentialsProvider with respect to an concrete AuthScope. The next step is to set them up on a HttpClientContext which then again needs to be provided to the engine.

Credentials credentials = new NTCredentials("user", "password", "workstation", "domain");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
  new AuthScope(null, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM)
  , credentials
);
HttpClientContext httpContext = HttpClientContext.create();
httpContext.setCredentialsProvider(credentialsProvider);
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
  ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, httpContext);
  ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
  // work with the client
}

Using URLConnectionEngine

This engine utilizes a HttpURLConnection which somehow invokes an Authenticator to do authentication. To provide the credentials you must override getPasswordAuthentication in a custom subclass and register it as default.

public class NTLMAuthenticator extends Authenticator {
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("domain\\user", "password".toCharArray());
  }
}
Authenticator.setDefault(new NTLMAuthenticator());
ResteasyClient client =
  new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()).build();
// work with the client
client.close();

Resources

irieill
  • 1,203
  • 10
  • 32