C# HttpClient integrated authentication

HttpClient has become the standard way to make http requests in C#. This is mainly used for API calls but has other uses as well. Recently, I have had to make http requests to servers that require authentication and the documentation on how to do this is scattered. The funny part is that it is really easy to do.

var uri = new Uri("<url>");

var credentialCache = new CredentialCache();
credentialCache.Add(
    new Uri(uri.GetLeftPart(UriPartial.Authority)),
            "<auth method>",
            new NetworkCredential("<user name>", "<password>", "<domain>")
            );
            

HttpClientHandler handler = new HttpClientHandler();
handler .Credentials = credentialCache;
var httpClient = new HttpClient(handler );

var response = httpClient.GetAsync(uri).Result;

<auth method> can be basic, digest, ntlm, or negotiate. Then just updated the Network Credentials to that of the user you want to make the call and you are good to go.

It appears that kerberos on its own does not work. This may be because of my server configuration. However if you use negotiate, HttpClient will use kerberos if the server is configured for it otherwise it will fallback to NTLM.

Tags: ,

2 Responses to “C# HttpClient integrated authentication”

  1. Sean Says:

    This helped me out. Thanks!

  2. mortb Says:

    As you say, when using Negotiate it fallback to NTLM if it fails to set up Kerberos. In our case it fell back to NTLM since you need to have a SPN registered for the DNS name you use when accessing the url.

Leave a Reply