When running within a website that uses impersonation you find it necessary sometimes to have your code stop impersonating for a period of time while you run some code. For example if you need to get off the box (not using Kerberos) and connect to another resource you will need to fall back and run as the AppPool account or logon another user and use those credentials to hit the remote resource. For the former I have written a small utility class that makes this possible. There are other samples out there however some use PINVOKE and I wanted something really simple and easy to use.

To use the code you will do something like:

using (new AppPoolImpersonator())

{

//unimpresonated code here

}

 

The class looks like so:

public class AppPoolImpersonator : IDisposable

{

WindowsImpersonationContext _windowsImpersonationContext;

 

public AppPoolImpersonator()

{

if (_windowsImpersonationContext == null &&

!WindowsIdentity.GetCurrent().IsSystem)

{

_windowsImpersonationContext = WindowsIdentity.Impersonate(System.IntPtr.Zero);

}

}

 

public void Dispose()

{

Undo();

GC.SuppressFinalize(this);

}

 

public void Undo()

{

if (_windowsImpersonationContext != null)

{

_windowsImpersonationContext.Undo();

_windowsImpersonationContext = null;

}

}

}