JH_Dev
JH_Dev

Reputation: 446

Passing Credentials works for WebRequest but not for HttpClient

I'm trying to pass credentials back to a web service using HttpClient. However, I keep getting an Unauthorized request. However, when I try using a WebRequest it authenticates?

HttpClient:

        var handler = new NativeMessageHandler
        {
            UseDefaultCredentials = true,
            Credentials = credential
        };
        var client = new HttpClient(handler);
        var content = _httpClientHelper.Serialize(data);
        var response = await _client.PostAsync($"{_baseurl}/api/foos/List", content);

WebRequest:

        HttpResponseMessage response = null;
        try
        {
            var data = JsonConvert.SerializeObject(new
            {
                ViewTitle = "New",
                PageCount = 60
            });

            var content = _httpClientHelper.Serialize(data);

            using (var client = new WebClient { UseDefaultCredentials = true, Credentials = credentials })
            {

                client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
                client.UploadData("$"{baseurl}/api/foos/List", "POST", Encoding.UTF8.GetBytes(content));
            }

I cannot figure out why one works and the other does not. Any help or insight on this would be greatly appreciated

Upvotes: 2

Views: 650

Answers (1)

NGambit
NGambit

Reputation: 1181

As noted here and here this behavior of HttpClient could be because of how HttpClientHandler is implemented.

"[..] the StartRequest method is executed in new thread with the credentials of the asp.net process (not the credentials of the impersonated user) [..]"

You might be seeing the difference in behavior of HttpClient and WebClient because

"HttpClient creates new threads via the Task Factory. WebClient on the other hand, runs synchronously on the same thread thereby forwarding its credentials (i.e. the credentials of the impersonated user) ."

Upvotes: 2

Related Questions