Programmatic Impersonation

It is often a requirement in your web application to run with impersonation on. This ensures that the users credentials are directly related to whoever is logged in. However, sometimes you need access to a local file system in which that user may not have access too. What you can do is give access to the App Pool Identity associated with the web application, and then simply turn impersonation off programmatically while you access that directory. Of course once you are finished you need to turn it back on.

Check it out:

  1.  
  2. // Stop impersonation
  3. WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
  4. try
  5. {
  6.      // Thread is now running under the process identity.
  7.      // Any resource access here uses the process identity.
  8.  
  9.      // TODO: Complete required actions safely (even if it fails, it will revert back to original identity).
  10. }
  11. finally
  12. {
  13.      // Resume impersonation
  14.      ctx.Undo();
  15. }

2 Comments

  1. Jeremy says:

    Although, technically, you are not “disabling” impersonation here, but rather just changing the impersonated context to that of the account used by the App pool… But that works… same effect, I suppose.

  2. Sheil says:

    You should put WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero); inside the try – that way you are sure that once impersonation has completed the finally will be called.

Leave a Reply to Jeremy