4

Working with the Mongo Atlas API in a .Net Core 3.1 application, but I cannot get HttpClient to handle the challenge from Digest Authentication.

The code sends the first request, gets a 401 response, and then doesn't resend with proper authentication.

Below is the code I've been trying to get working

var domain = "https://cloud.mongodb.com/";
var credCache = new CredentialCache();
credCache.Add(new Uri(domain),"Digest", new NetworkCredential(user,secret));
var httpClient = new HttpClient( new HttpClientHandler { Credentials = credCache});
var answer = await httpClient.GetAsync(new Uri($"{domain}api/atlas/v1.0/groups/{groupId}/databaseUsers"));

Here's the response I'm getting

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Mon, 27 Jan 2020 21:03:14 GMT
  WWW-Authenticate: Digest realm="MMS Public API", domain="", nonce="generatedNonce", algorithm=MD5, qop="auth", stale=false
  Content-Type: application/json
  Content-Length: 106
}

I've sent curl requests successully so I'm certain my user/secret/group are correct.

Does anyone see something wrong with that code, or know what I can do to further debug this issue?

Eric
  • 231
  • 3
  • 9

1 Answers1

7

Apparently we have the exact same problem or I had at least until my colleague found a solution for it.

There was a lot of changes to HttpClient internals in 2.1 to support the new SocketsHttpHandler, use this line of code to go back to the 2.0 functionality and it should work again, put it Main or somewhere before the calls you are making.

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

Otherwise you'd have to first send one request get the 401 response grab the nonce from the WwwAuthenticate header and you probably also need to set some more fields in the header.

Cheers!

Found it in this post on reddit: https://www.reddit.com/r/dotnet/comments/9yailz/weird_dotnet_core_httpclient_bug_maybe/ea07edd/

  • This workaround is no longer working in .Net 5, has anyone found a solution? – Sivan Krigsman Jan 07 '21 at 19:30
  • I ended up creating a custom handler similar to https://stackoverflow.com/questions/3109507/httpwebrequests-sends-parameterless-uri-in-authorization-header – Eric Mar 02 '21 at 18:41
  • @Eric you should post the handler if it worked for you no ? – David Noreña Mar 08 '21 at 08:30
  • 1
    If anyone else is looking for a more in detail answer to this will a full implementation, I made a blog post to show how it can be done 'from scratch': https://dev.to/callumhoughton18/implementing-digest-authentication-in-net-396j – Callum Houghton May 24 '22 at 19:53
  • I just copy pasted all the methods in @CallumHoughton 's link and got it to work, nice 1! – WtFudgE Mar 13 '23 at 04:25