在.Net Core 3.1应用程序中使用Mongo Atlas API,但我无法获得HttpClient
来处理摘要身份验证带来的挑战。
该代码发送第一个请求,获得401响应,然后不通过适当的身份验证重新发送。
下面是我一直尝试使用的代码
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"));
这是我得到的答复
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
}
我已经成功发送了curl请求,因此我确定我的用户/秘密/组是正确的。
有人看到该代码有问题吗,或者知道我可以做些什么来进一步调试此问题?
显然,我们遇到了完全相同的问题,或者至少在我的同事找到解决方案之前,我遇到了这个问题。
2.1中的HttpClient内部进行了很多更改以支持新的SocketsHttpHandler,使用此行代码返回2.0功能,它将再次起作用,将其放置在Main
或进行调用之前的某个位置。
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
否则,您首先必须发送一个请求,以从401
标头中获取nonce
响应,并抓住WwwAuthenticate
,并且您可能还需要在标头中设置更多字段。
干杯!
在reddit上的这篇文章中找到它:https://www.reddit.com/r/dotnet/comments/9yailz/weird_dotnet_core_httpclient_bug_maybe/ea07edd/