。Net Core HttpClient摘要身份验证

问题描述 投票:1回答:1

在.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请求,因此我确定我的用户/秘密/组是正确的。

有人看到该代码有问题吗,或者知道我可以做些什么来进一步调试此问题?

c# asp.net-core digest-authentication
1个回答
0
投票

显然,我们遇到了完全相同的问题,或者至少在我的同事找到解决方案之前,我遇到了这个问题。

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/

© www.soinside.com 2019 - 2024. All rights reserved.