When working with web applications, especially on intranet sites, you sooner or later find yourself dealing with impersonation issues. My last problem was caused by the default impersonation when hosting classic Asp in IIS.

I found that my WCF service calls failed upon authentication, digging hard and long, I found that the request being made (using MS Network Monitor since I used netTcp binding instead of glorious and humanly readable http) was sending the logged-in user account in one case whilst sending proper identityPrincipalName in my local test application.

So, how to solve this? I needed the request to be made using the application pool service account since this has all the privileges to the service and I didn’t want to go through the trouble of trying to enable some kind of second-level delegation. Turns out there is a simple yet effective way to revoke or undo the impersonation:

WindowsImpersonationContext impersonationContext = null;

try {
    // Examine the current impersonation and reset to not using if set to a user account
    var currentIdentity = WindowsIdentity.GetCurrent ();
    if (currentIdentity != null && currentIdentity.IsSystem == false)
        impersonationContext = WindowsIdentity.Impersonate (IntPtr.Zero);

    // Do your stuff

} finally {
    // Restore the impersonation if we managed to revoke it
    if (impersonationContext != null)
        impersonationContext.Undo ();
}