提问者:小点点

带有NTLM身份验证的C#HttpClient未传递正确的凭据


有两个ASP.NET核心API,其中API A具有基本身份验证,API B具有windows身份验证。API A正在调用API B,但由于API B启用了windows身份验证,因此API A需要具有NTLM身份验证的httpclient

API A(简体):

var ccahe = new CredentialCache
{
    {
        httpRequestMessage.RequestUri, "NTLM",
        new NetworkCredential("a.antr01", "pw", "ICEPOR")
    }
};
var httpClientHandler = new HttpClientHandler()
{
    PreAuthenticate = true,
    Credentials = ccahe,
    UseDefaultCredentials = true,
    AllowAutoRedirect =  true
};

using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
    return await httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead);
}

正如您在上面的代码片段中所看到的,我有一个HttpClient,其用户为a.antr01,但在API B中的调试器中,在声明转换代码中,我看到了my用户,该用户登录在Windows中,并在该帐户下运行IDE:

如何将支持NTLM的API A的请求发送到API B,并且API B将具有正确的凭据?

编辑:如果有一种方法可以在API B中同时支持basic和NTLM身份验证,那么API a就不再需要了,也许有人知道如何实现?

因此,基本身份验证流程将为解码Base64->针对AD进行身份验证->获取授权声明->继续到控制器

NTLM身份验证将为(已通过身份验证)->获取授权声明->继续到控制器


共2个答案

匿名用户

为了理智起见,你能用仅仅

var httpRequestMessage = ...; // whatever it's expecting

var httpClientHandler = new HttpClientHandler()
{
    PreAuthenticate = true,
    Credentials = new NetworkCredential("a.antr01", "pw", "ICEPOR"), // real password instead of "pw"
    AllowAutoRedirect =  true
};

using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
    return await httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead);
}

看看API B中发生了什么?

匿名用户

我可以为你的编辑提供解决方案。在WebAPI中同时实现windows和基本身份验证的唯一方法是使用特定位置进行基本身份验证:web.config

<configuration>
    <system.web>
        <authentication mode="Windows" />
    </system.web>


  <location path="api/mypath">
    <system.webServer>
      <security>
        <authentication>
          <basicAuthentication defaultLogonDomain="mydomain" enabled="true" realm="myrealm" />
        </authentication>
      </security>
    </system.webServer>
  </location>

</configuration>

因此对/API/MyPath/MyController的所有请求都需要基本身份验证。所有其他请求/API/SomeOtherPath/SomeOtherController将使用windows身份验证。

您可以将控制器与[system.web.http.route(“API/MyPath/MyController”)]重新匹配

在IIS服务器中,so应同时启用Windows身份验证和基本身份验证。之后,web.config就会启动(您可能还必须配置IIS配置文件以启用这两种身份验证类型)。

如果您不坚持在同一个端点上使用NTLM和basic->,这可能是您的解决方案。

除此之外,我使用几乎完全相同的代码连接到带有NTLM的API:

var credentialsCache = new CredentialCache
{{builder.Uri, "NTLM", new NetworkCredential(
    "user",
    "password",
    "domain"
)}};
var handler = new HttpClientHandler { Credentials = credentialsCache };
var client = new HttpClient(handler);
await client.PostAsync(url, data).ConfigureAwait(false);