c# - .Net Core HttpClient 摘要身份验证

标签 c# asp.net-core digest-authentication

在 .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 请求,所以我确定我的用户/ secret /组是正确的。

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

最佳答案

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

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/

关于c# - .Net Core HttpClient 摘要身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939357/

相关文章:

ruby-on-rails - 为 HTTP 摘要认证编写测试/方法

Tomcat JDBC 与数据源领域

c# - 创建现有程序集/模块的动态副本

c# - 为什么 Linq 无法搜索阿拉伯文本?

c# - 如何在通过HTTPClientFactory创建的HTTPClient实例中访问CookieContainer

asp.net-core - CKEDITOR 文件上传错误请求 400 错误

javascript - 使用 Javascript XMLHttpRequest 的摘要认证

c# - 如何将 ObservableCollection<T> 绑定(bind)到 WrapPanel?

C# Linq问题

c# - ASP.NET Core 中的内容类型 "415 Unsupported Media Type"为 "application/csp-report"