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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.