2

I am building an application that reads JSON response from certain endpoints and I am trying to authenticate in Apache HttpClient using NTLM authentication:

The class that is responsible for authentication HttpConnector tries to authentice right after its instantiation:

public static HttpConnector on(String username, String password) {
        HttpConnector connector = new HttpConnector(username, password);
        Credentials credentials = new NTCredentials(username, password, "host", "domain");
        connector.getHttpClient().getState().setCredentials(AuthScope.ANY, credentials);
        return connector;
    }

but I always get response code 401 Unauthorized. As I read in internet including here in Stackoverflow I used NTCredentials that I am trying to set globally in the HttpClient. I have tested the endpoints in Postman, there I get the JSON response successfully but HttpClient cannot connect.

In the code I use GetMethod: httpMethod = new GetMethod(url); Here I have also tried to configure authentication but it still does not work:

private void configureMethod(HttpMethod httpMethod) throws MalformedChallengeException {
        httpMethod.getHostAuthState().setAuthRequested(true);
        httpMethod.setRequestHeader("Content-Type",  "application/json; charset=UTF-8");
        httpMethod.setDoAuthentication(true);
        httpMethod.getParams().setParameter(
                HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        httpMethod.getHostAuthState().setAuthRequested(true);
        httpMethod.getHostAuthState().setAuthScheme(
                new NTLMScheme(
                          String.format("ntlm %s:%s", username, password)));

}

During debugging I see that I get: Connection reset by peer: socket write error. It happens in HttpMethodDirector::executeWithRetry(final HttpMethod method) method.

enter image description here

Can someone help me, what is the correctNTLM authentication setup in Apache HttpClient. Can I really use the global set of credentials or I have to setup credentials to every HttpMethod I create and how?

Thank you in advance!

Rosen Hristov
  • 61
  • 1
  • 7

1 Answers1

1

I fixed this by formatting the client the following way:

HttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new NTCredentials(username, password, HOST, MY_DOMAIN));

And the used not GetMethod but HttpGet:

HttpGet = getRequest = new HttpGet(url);

and this time the connection owas successful.

Rosen Hristov
  • 61
  • 1
  • 7