问题
I have a Microsoft.Rest.ServiceClient
generated with autorest
. And I want to access a REST API secured with Windows Authentication and Basic Authentication.
The goal is to use Windows Authentication. I tried it as follows:
var handler = new HttpClientHandler
{
UseDefaultCredentials = true,
};
this.InitializeHttpClient(handler);
This does not work, I get:
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
When I use Basic Authentication it works.
this.Credentials = new BasicAuthenticationCredentials
{
UserName = Configuration.User,
Password = Configuration.Password
};
This setup of the ServiceClient
is done in the constructor of
MyClient : Microsoft.Rest.ServiceClient
What do I need to add to the client to get Windows Authentication working?
Edited:
It looks like the problem is on server side. Settings in IIS.
The client would work as expected.
回答1:
This basically reiterates what's already covered in the OP and by @Anders, in my preferred syntax...
var windowsAuthHandler = new HttpClientHandler { UseDefaultCredentials = true };
var webApiUri = new System.Uri("https://localhost:8080");
var apiClient = new MyAutoRestClient(webApiUri ,windowsAuthHandler);
If you're skimming, the OP seems to indicate this doesn't work, when, indeed it does. But, as the OP later states, be sure to start with IIS to make sure it's configured right
回答2:
I use a similar solution for passing on Windows credentials, and it works nicely.
The only difference is that I use the constructor overload of ServiceClient
that takes a HttpClientHandler
instance, rather than calling InitializeHttpClient()
and it looks something like this:
public class MyClient : ServiceClient<MyClient>
{
public MyClient() : base(new HttpClientHandler { UseDefaultCredentials = true }) {}
}
However, the part of your 401-message that says "The target principal name is incorrect" looks suspicious. Your problem may arise from some issues in your AD-configuration rather than in the ServiceClient
-configuration.
来源:https://stackoverflow.com/questions/49902131/how-can-i-use-windows-authentication-with-microsoft-rest-serviceclient