简体   繁体   中英

IIS 7.5 Web Application returns Unauthorized when using HttpClient

I have a web application which is hosted in IIS 7.5 on Windows Server 2008 R2 and on another test machine in IIS 8.5 on Windows Server 2012 R2. Windows Authentication is enabled and the Application Pool is running under a service account like "DomainName\\DomainUsername".

I'm using a small C# Console test application to intantiate an HttpClient object and call a controller action of the website, eg http://localhost/Api/TestAction . Both test systems behave differently and i do not understand why.

  • Test Case 1) without credentials
  • Test Case 2) with "default credentials"
  • Test Case 3) with the credentials of the user of the apppool ("DomainName\\DomainUsername")

TestCase 1:

HttpClient client = new HttpClient();
var response = client.GetAsync(url).Result;
Console.WriteLine(response.StatusCode); 

TestCase 2:

HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
var response = client.GetAsync(url).Result;
Console.WriteLine(response.StatusCode);

TestCase 3:

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
HttpClient client = new HttpClient(handler);
var response = client.GetAsync(url).Result;
Console.WriteLine(response.StatusCode);

Here are the results:

Windows Server 2008 R2 (IIS 7.5):

  • Test Case 1 - Unauthorized
  • Test Case 2 - OK
  • Test Case 3 - Unauthorized

Windows Server 2012 R2 (IIS 8.5):

  • Test Case 1 - Unauthorized
  • Test Case 2 - OK
  • Test Case 3 - OK

Could you please help me to understand why both test systems give different results for Test Case 3 (using credentials of the apppool user)? And could you please explain what "UseDefaultCredentials" mean and what impact does this have on the authorization issue? So far I haven't found an explanation that i understand.

Thanks!

An answer accepted by the OP in the discussion below the question involves calling the NetworkCredentials constructor with three arguments rather than two, the third one being the domain name.

In other words, this one works

NetworkCredentials("Username", "Password", "Doamin")

where this one doesn't

NetworkCredentials("Domain\Username", "Password")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM