title: How do I handle WindowsImpersonationContext with HttpListener?
body: <p>This may have been asked previously a slightly different way, but I have not yet satisfied myself completely.</p>
  
  <p>With <strong>Visual Studio 2013, Windows 7, and a small C#/.NET 4.0</strong> project, I am using an HttpListener to build a tiny web server in order to host some simple services and pages.  Part of an upgrade to the existing project here was to start using integrated windows authentication.</p>
  
  <p>One of the services this project offers is a way to connect to a SQL database - in order to run some canned updates.  Using WindowsImpersonationContext and the correct HttpListener startup parameters, I was easily able to "impersonate" the authenticated user (via NTLM).  Like so:</p>
  
  <pre><code>identity = (System.Security.Principal.WindowsIdentity)context.User.Identity;
  
  using (System.Security.Principal.WindowsImpersonationContext wic = identity.Impersonate())
  {
      doListenerCallback(context, lentry, true, identity);
  }
  </code></pre>
  
  <p>The idea is that the credentials of the user accessing the web page is what's used to open the database connection. So this code is fine, and it gives me back an object, and all seems well.</p>
  
  <p>Everything works correctly <strong>until</strong> I run this project (it is hosted inside a console app) using a <strong>regular</strong> user account (non-administrator).  Impersonation still appears to happen, but my appdomain no longer allows assembly loading.  I get stuff like this:</p>
  
  <pre><code>fact = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
  </code></pre>
  
  <p>Results in:</p>
  
  <blockquote>
    <p>A first chance exception of type 'System.IO.FileLoadException'
    occurred in mscorlib.dll</p>
    
    <p>Additional information: Could not load file or assembly
    'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral,
    PublicKeyToken=b77a5c561934e089' or one of its dependencies. Either a
    required impersonation level was not provided, or the provided
    impersonation level is invalid. (Exception from HRESULT: 0x80070542)</p>
  </blockquote>
  
  <p>And I can't seem to do anything to get beyond this.  I read elsewhere that it might be because a low priv account can't impersonate an admin account, at least without a UAC prompt.</p>
  
  <p>If that is true, how does IIS manage to do this?  Because I've done a lot of crazy ASP.Net stuff with impersonation, and never encountered this before.</p>
  
  <p>We can certainly run this tool with an admin service account.  But it just seems silly to do that - if impersonation exists, and it exists exactly for this kind of purpose, I'd like to know what I'm doing wrong and why it isn't working. </p>