.Net Core HttpClient摘要身份验证 [英] .Net Core HttpClient Digest Authentication

查看:154
本文介绍了.Net Core HttpClient摘要身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.Net Core 3.1应用程序中使用Mongo Atlas API,但是我无法获得 HttpClient 来处理摘要身份验证带来的挑战.

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.

该代码发送第一个请求,获得401响应,然后不使用适当的身份验证重新发送.

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"));

这是我得到的答复

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

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?

推荐答案

显然我们遇到了完全相同的问题,或者直到我的同事找到解决方案为止.

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

2.1中对HttpClient内部进行了很多更改以支持新的SocketsHttpHandler,使用此行代码返回到2.0功能,它应该可以再次使用,将其放置在 Main 或某处在拨打电话之前.

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);

否则,您必须首先发送一个请求,以获取 401 响应,并从 WwwAuthenticate 标头中获取 nonce ,您可能还需要在标题中设置更多字段.

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.

干杯!

在reddit上的此帖子中找到了它: https://www.reddit.com/r/dotnet/comments/9yailz/weird_dotnet_core_httpclient_bug_maybe/ea07edd/

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

这篇关于.Net Core HttpClient摘要身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆