14

I am trying to use the HttpClient to access a REST service which requires NTLM authentication. However I keep getting a 401 Unauthorized. My code looks like this

    private static void Main()
    {
        var uri = new Uri("http://localhost:15001");
        var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
        var handler = new HttpClientHandler { Credentials = credentialsCache };
        var httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = httpClient.GetAsync("api/MyMethod").Result;
    }

My target framework is netcoreapp2.0. If I change to net461, it will work. Not sure what I am doing wrong?

jps
  • 20,041
  • 15
  • 75
  • 79
Torben Nielsen
  • 663
  • 1
  • 8
  • 21

2 Answers2

9

Microsoft has accepted this as a bug. Possibly a fix will be released with core 2.1

https://github.com/dotnet/corefx/issues/25988

Torben Nielsen
  • 663
  • 1
  • 8
  • 21
0

Default NTLM authentication and Kerberos authentication use the Microsoft Windows user credentials associated with the calling application to attempt authentication with the server. When using non-default NTLM authentication, the application sets the authentication type to NTLM and uses a NetworkCredential object to pass the user name, password, and domain to the host, as shown in the following example.

string myUri = "http://www.contoso.com/";
using HttpClientHandler handler = new()
{
    Credentials = new NetworkCredential(UserName, SecurelyStoredPassword, Domain),
};
using HttpClient client = new(handler);
string result = await client.GetStringAsync(myUri);
// Do Other Stuff...

Applications that need to connect to Internet services using the credentials of the application user can do so with the user's default credentials, as shown in the following example.

string myUri = "http://www.contoso.com/";
using HttpClientHandler handler = new()
{
    Credentials = CredentialCache.DefaultCredentials,
};
using HttpClient client = new(handler);
string result = await client.GetStringAsync(myUri);
// Do Other Stuff...

The negotiate authentication module determines whether the remote server is using NTLM or Kerberos authentication, and sends the appropriate response.

https://learn.microsoft.com/en-us/dotnet/framework/network-programming/ntlm-and-kerberos-authentication

In other words, NTLM authentication is implicit.

GPManuel
  • 1
  • 2