[英]How to use Microsoft.Rest.ServiceClient<> with client certificate?
[英]How can I use Windows Authentication with Microsoft.Rest.ServiceClient
我有一个使用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 中的设置。
客户端将按预期工作。
这基本上重申了 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 开始以确保其配置正确
我使用类似的解决方案来传递 Windows 凭据,并且效果很好。 唯一的区别是我使用ServiceClient
的构造函数重载,它接受一个HttpClientHandler
实例,而不是调用InitializeHttpClient()
,它看起来像这样:
public class MyClient : ServiceClient<MyClient>
{
public MyClient() : base(new HttpClientHandler { UseDefaultCredentials = true }) {}
}
但是,您的 401 消息中说“目标主体名称不正确”的部分看起来很可疑。 您的问题可能源于 AD 配置中的某些问题,而不是ServiceClient
配置中的问题。
@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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.