Compartir a través de


Run (As Your AppPool Account) Forrest

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;

}

}

}

Comments

  • Anonymous
    February 11, 2009
    PingBack from http://www.clickandsolve.com/?p=6654

  • Anonymous
    March 11, 2009
    Hi Todd, how is this any different from using SPSecurity.RunWithElevatedPrivileges()? Kind regards, Matthias

  • Anonymous
    March 15, 2009
    Its not other than I was not offering this up as necessarly a SharePoint solution, that is, this basically will work for any ASP.Net web application not just SharePoint. So if you are writing a WebPart and you would like the flexibility of it being used in ASP.Net and SharePoint the above pattern will work.