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?

1 Answer 1

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/

5
  • This workaround is no longer working in .Net 5, has anyone found a solution? Jan 7, 2021 at 19:30
  • I ended up creating a custom handler similar to stackoverflow.com/questions/3109507/…
    – Eric
    Mar 2, 2021 at 18:41
  • @Eric you should post the handler if it worked for you no ? Mar 8, 2021 at 8: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': dev.to/callumhoughton18/… May 24, 2022 at 19:53
  • I just copy pasted all the methods in @CallumHoughton 's link and got it to work, nice 1!
    – WtFudgE
    Mar 13 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.