Search code examples
resthttphttp-postwindows-authenticationntlm

Http post requests unsing NTLM Authentication (java)


I tried to send a HttpRest Call using NTLM Autentication in Java. I tried using the org.apache.http library. it was not a big problem to use the HttpClient to send a Post Request with anonymos authentication. But i have some troubles with WindowsAuthentication. I even tried to use CredentialProvider with my own Windows credentials (as a compromise, i dont like that either) but i didn’t succeed.

Is there an easy way using NTLM Authentication sending post requests from Java code?

Is there another lib which fits better form my needs?


Solution

  • I still have no idea why the docs from https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html about NTLM Authentication didn’t have worked for me.

    I finally solved my problem by doing it similar to the documentation for basic authentication as described on http://www.baeldung.com/httpclient-post-http-request

    It now looks like this:

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(username, password, workstation, domain));
    
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build()) {
        HttpPost post = new HttpPost(url);
        
        StringEntity input = new StringEntity(body, "UTF-8");
        input.setContentType("application/json");
        input.setContentEncoding("UTF-8");
        
        post.setEntity(input);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");
    
        HttpResponse response = client.execute(post);
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }