【问题标题】:How can I use Windows Authentication with Microsoft.Rest.ServiceClient如何将 Windows 身份验证与 Microsoft.Rest.ServiceClient 一起使用
【发布时间】:2018-09-28 20:07:56
【问题描述】:

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

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

var handler = new HttpClientHandler
{
    UseDefaultCredentials = true,
};
this.InitializeHttpClient(handler);

这不起作用,我明白了:

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

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

this.Credentials = new BasicAuthenticationCredentials
{
    UserName = Configuration.User,
    Password = Configuration.Password
};

ServiceClient 的设置是在

的构造函数中完成的
MyClient : Microsoft.Rest.ServiceClient

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

已编辑:

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

客户端会按预期工作。

【问题讨论】:

  • 进程是在您的 Windows 主体还是其他帐户下运行?
  • 我都试过了,但正如问题中提到的,客户炒锅是正确的。

标签: c# .net windows-authentication autorest


【解决方案1】:

这基本上以我的首选语法重申了 OP 和 @Anders 已经涵盖的内容...

 var windowsAuthHandler = new HttpClientHandler { UseDefaultCredentials = true };
 var webApiUri = new System.Uri("https://localhost:8080");
 var apiClient = new MyAutoRestClient(webApiUri ,windowsAuthHandler);

如果您正在略读,OP 似乎表明这不起作用,实际上它确实起作用。但是,正如 OP 后面所述,请务必从 IIS 开始,以确保其配置正确

【讨论】:

    【解决方案2】:

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

    public class MyClient : ServiceClient<MyClient>
    {
        public MyClient() : base(new HttpClientHandler { UseDefaultCredentials = true }) {}
    }
    

    但是,401 消息中“目标主体名称不正确”的部分看起来很可疑。您的问题可能来自您的 AD 配置中的某些问题,而不是 ServiceClient-配置中的一些问题。

    【讨论】:

      【解决方案3】:

      @bkwdesign 说得对

      var credentials = new Microsoft.Rest.BasicAuthenticationCredentials();
      var handler = new System.Net.Http.HttpClientHandler() { UseDefaultCredentials = true };
      var uri = new Uri("http://your-rest-api:8008");
      var svc = new WebApplication1Client(uri, credentials, handler);
      
      //WebApplication1Client : ServiceClient<WebApplication1Client>, IWebApplication1Client
      

      这是如何将凭据从 MVC 传递到 WebAPI Windows 身份验证或模拟凭据的方式

      也许还有其他选择:

      var handler = new HttpClientHandler() { Credentials = CredentialCache.DefaultCredentials };
      var handler = new HttpClientHandler() { Credentials = CredentialCache.DefaultNetworkCredentials };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        • 2011-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        相关资源
        最近更新 更多