如何在 Microsoft.Rest.ServiceClient 中使用 Windows 身份验证

Hei*_*ner 6 .net c# windows-authentication autorest

我有一个Microsoft.Rest.ServiceClient生成的autorest. 我想访问受 Windows 身份验证和基本身份验证保护的 REST API。

目标是使用 Windows 身份验证。我试过如下:

var handler = new HttpClientHandler
{
    UseDefaultCredentials = true,
};
this.InitializeHttpClient(handler);
Run Code Online (Sandbox Code Playgroud)

这不起作用,我得到:

System.Net.Http.HttpRequestException: An error occurred while sending the request. 
---> System.Net.WebException: The remote server returned an error: (401) Unauthorized. 
---> System.ComponentModel.Win32Exception: The target principal name is incorrect
Run Code Online (Sandbox Code Playgroud)

当我使用基本身份验证时,它可以工作。

this.Credentials = new BasicAuthenticationCredentials
{
    UserName = Configuration.User,
    Password = Configuration.Password
};
Run Code Online (Sandbox Code Playgroud)

这个设置ServiceClient是在构造函数中完成的

MyClient : Microsoft.Rest.ServiceClient
Run Code Online (Sandbox Code Playgroud)

我需要向客户端添加什么才能使 Windows 身份验证正常工作?

编辑:

看起来问题出在服务器端。IIS 中的设置。

客户端将按预期工作。

And*_*ers 0

我使用类似的解决方案来传递 Windows 凭据,并且效果很好。唯一的区别是我使用了ServiceClient需要HttpClientHandler实例的构造函数重载,而不是调用InitializeHttpClient(),它看起来像这样:

public class MyClient : ServiceClient<MyClient>
{
    public MyClient() : base(new HttpClientHandler { UseDefaultCredentials = true }) {}
}
Run Code Online (Sandbox Code Playgroud)

但是,401 消息中显示“目标主体名称不正确”的部分看起来很可疑。您的问题可能是由于 AD 配置中的某些问题而不是 ADServiceClient配置中的问题引起的。