0

I have been able to successfully authentication to a service that requires ntlm authentication when using the WinHttpClients and a GET request. However when I try to do a POST I always get a 401 return code. Has anyone done this sucessfully before?

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.WinHttpClients;


public class WindowsAuthPOst {

public static void main (String []args) throws Exception, IOException
{
    org.apache.log4j.BasicConfigurator.configure();
    CloseableHttpClient httpclient = WinHttpClients.createDefault();

    HttpHost target = new HttpHost("SomeHost.domain", 443, "https");

    HttpClientContext context = HttpClientContext.create();
    HttpGet httpget = new HttpGet("/some/Service.svc");
    CloseableHttpResponse response1 = httpclient.execute(target, httpget, context);
    try {
        HttpEntity entity1 = response1.getEntity();
    } finally {
        response1.close();
    }

    // Execute an expensive method next reusing the same context (and connection)
    HttpPost httppost = new HttpPost("/some/Service.svc");
    httppost.setHeader("SOAPAction", "Some Soap Action");
    httppost.setEntity(new StringEntity("Soap Payload"));
    CloseableHttpResponse response2 = httpclient.execute(target, httppost, context);
    try {
        HttpEntity entity2 = response2.getEntity();
    } finally {
        response2.close();
    }
}

}

Radford7821
  • 335
  • 3
  • 11

2 Answers2

0

You can check if it is available with.

    if (!WinHttpClients.isWinAuthAvailable()) {
        System.out.println("Integrated Win auth is not supported!!!");
    }

If not, it could be that you do not have jna.jar in your classpath. It depends on jna and will silently return false on the above if it not there, see source code.

gustf
  • 1,959
  • 13
  • 20
0

Try with get (or options) before post. Some webservers requires that because of CORS. https://stackoverflow.com/a/38410411/2376661

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30432646) – Procrastinator Nov 26 '21 at 08:04