title: How to send client credentials for windows authentication from a client application to ensure user is not anonymous
body: <p>I have a client application that is attempting to issue requests to an IIS7 hosted web application. The client needs to send its identity to participate in windows authentication. This is akin to IE sending the user's credentials using windows integrated security. I need the same behaviour in a C# .net client application.</p>
  
  <p>The client issues requests using WebRequest class:</p>
  
  <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://webhost/resources/a"));
  request.Method = method;
  request.MaximumAutomaticRedirections = 10;
  request.UseDefaultCredentials = true;
  </code></pre>
  
  <p>This does not appear to work, since when impersonation is attempted on the server using code like:</p>
  
  <pre><code>WindowsIdentity windowsIdentity = (WindowsIdentity)HttpContext.Current.User.Identity;
  using (windowsIdentity.Impersonate())
  {
      // do stuff
  }
  </code></pre>
  
  <p>an exception occurs:</p>
  
  <pre><code>2011-08-24 15:42:12,949 [63] ERROR - Error occurred responding to PUT request for http://webhost:1234/resources/a. System.InvalidOperationException: An anonymous identity cannot perform an impersonation.
     at System.Security.Principal.WindowsIdentity.Impersonate(StackCrawlMark&amp; stackMark)
     at System.Security.Principal.WindowsIdentity.Impersonate()
  </code></pre>
  
  <p>Somehow, I need to ensure that the credentials are sent to the server so the server doesn't see the client as anonymous. I have been trying to disable anonymous authentication on the server but this throws up another error (this is another issue which I would rather not go into here; I've already posted another question regarding that).</p>