从 ASP.NET 服务发送带有 Windows 身份验证的请求

Sending a request with Windows Authentication from ASP.NET service

我有一个有效的 Python 脚本,它使用 Windows 身份验证向 Web 服务发送请求以获得令牌。

我要复制的位是:

url = 'https://ssologin.company.com/Logon/Logon.aspx?permission=permission'
h = WC.Dispatch('WinHTTP.WinHTTPRequest.5.1')
h.SetAutoLogonPolicy(0)
h.SetOption(6, False)
h.Open('GET', url, False)
h.Send()

我有一个 ASP.NET 核心服务试图这样做:

var uri = new Uri("https://ssologin.company.com/Logon/Logon.aspx?permission=permission");
WinHttpHandler handler = new WinHttpHandler();
handler.ServerCredentials = CredentialCache.DefaultNetworkCredentials;           
HttpClient httpClient = new HttpClient(handler);
var httpResponseMessage = await httpClient.GetAsync(uri);

现在我收到以下错误: WinHttpException: 错误 12029 调用 WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'A connection with the server could not be established'.

但是,如果我评论 // handler.ServerCredentials = CredentialCache.DefaultNetworkCredentials;,则会收到错误 401 未经授权。我还注意到 CredentialCache.DefaultNetworkCredentials 是 NULL。

你能告诉我我在这里缺少什么吗?谢谢。

实际上,身份验证工作正常,但请求重定向到拒绝连接的服务。解决这个问题的简单方法是禁用重定向。另外,在@spzvtbg 的建议下,我使用了默认的 HttpClienthandler.

最后的代码是这样的:

var uri = new Uri("https://ssologin.company.com/Logon/Logon.aspx?permission=permission");
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
handler.PreAuthenticate = true;
handler.AllowAutoRedirect = false;
HttpClient httpClient = new HttpClient(handler);
var httpResponseMessage = await httpClient.GetAsync(uri);