2

I'm trying to access a file in a web site using HttpClient, but I'm getting 401 Unauthorized.

The web site is configured with

<authentication mode="Windows" /> 
...
<authorization>
  <allow users="*" />
</authorization>

And the IIS is configured for Windows Authentication only.

I'm able to access the file using Internet Explorer by specifing the address in the URL and I'm NOT prompted for username/password.

When trying to do the "same" using HttpClient, I get 401 Unauthorized.

var httpClientHandler = new HttpClientHandler { UseDefaultCredentials = true };

using (var httpClient = new HttpClient(httpClientHandler))
{
    var response = httpClient.GetAsync("http://example.com/welcome.png");
    // The response is 401 Unauthorized.
}

What am I doing wrong?

UPDATE:

It works when using Basic Authentication and specifying httpClientHandler.Credentials = new NetworkCredential("DOMAIN\my.name", "mypassword"), but it goes without saying that that is not an option. Windows authentication and not having to specify username / password is desired.

Morzy
  • 47
  • 2
  • 7

1 Answers1

0

You are able to view the file in IE as you are already logged into the machine and IE takes care of passing on the tokens/tickets (generated after successful login) to the server to pass through Windows authentication.

You can refer to MSDN and find out how to get through Windows authentication using HTTPClient http://social.msdn.microsoft.com/Forums/windowsapps/en-US/78c981f4-9dc6-4785-a8ff-f8e90d7c93b7/is-there-a-way-to-get-windows-authentication-with-httpclient

Roshith
  • 2,116
  • 13
  • 21
  • Yeah, I mentioned IE to prove that the IIS setup was working. I found that it works with Basic Authentication when specifying httpClientHandler.Credentials = new NetworkCredential("DOMAIN\\my.name", "mypassword"), but I need it to work without having to "manually" specify credentials and with WinAuth. I read the article you linked to, but I failed to see what you think I'm missing? I specified UseDefaultCredentials = true. defaultWindowsCredentials and privateNetworkClientServer seem to be related to Windows Phone and I'm working on a WPF application. – Morzy Sep 01 '14 at 13:24
  • Well , I don't know much about WPF APIs. I think you could use WebRequestHandler as mentioned in the comments section here -- http://www.asp.net/web-api/overview/security/integrated-windows-authentication ---------------------------------------------------- WebRequestHandler handler = new WebRequestHandler() { AllowAutoRedirect = false, UseProxy = false, Credentials = System.Net.CredentialCache.DefaultNetworkCredentials }; HttpClient client = new HttpClient(handler)-------------------------- – Roshith Sep 02 '14 at 06:25