Welcome to MSDN Blogs Sign in | Join | Help

Todd's Blog

My contribution to the SharePoint community
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;

}

}

}

Posted: Wednesday, February 11, 2009 9:58 PM by Toddca

Comments

Matthias Glubrecht said:

Hi Todd,

how is this any different from using SPSecurity.RunWithElevatedPrivileges()?

Kind regards, Matthias

# March 12, 2009 6:46 AM

Toddca said:

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.

# March 15, 2009 12:32 PM
New Comments to this post are disabled
Page view tracker