Impersonating Current App Pool User

Using SharePoint it’s easy to run a block of code with elevated permissions:

SPSecurity.RunWithElevatedPrivileges(()=>
{
    using (SPSite elevatedSite = new SPSite(siteId))
    {
        using (SPWeb elevatedWeb = elevatedSite.OpenWeb(wedId))
        {
            // operations using elevated SPWeb object...
        }
    }
});

This is fine for SharePoint related impersonations. Any code executed within the elevated block that authenticates using an object instantiated outside the RunWithElevatedPrivileges block will run using the context of the current user and not the elevated account. So for example, if you wanted to make a web method call using a single user (or connect to a database) and not the current context, the following code block will achieve this for you:

using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(System.IntPtr.Zero))
{
    try
    {
        // code to run under the context of the current application pool identity.
 
    }
    catch (Exception ex)
    {
        // error loging, etc.
        throw;
    }
    finally
    {
        context.Undo();
    }
}

Of course, within SharePoint, if you want a set of processes to run under the context of a specific user, it would be better to contain the code within a service application (for example) which will run under the context of the defined managed account and not the current user context.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: