R – Methods of running with Elevated Privileges in a MOSS Publishing Site

mosssharepointsharepoint-2007

I am wondering why the two methods listed below do not give the same security trimming.

Expected result: Both methods give full access to all content in the current site collection

Actual result: Security trimming is occurring when using Method #1

  • Method #2 works properly for retrieving content from other webs, but Method #1 does not.

  • Both methods give access across webs in Anonymous mode, and both work for site admin accounts.

  • The difference comes for Hierarchy Managers, Approvers and Editors. Method #1 does not give admin access across webs.

Method #1

using (SystemOperation op = new SystemOperation())
{ 
    //Do an operation that requires retrieving across webs
}

public class SystemOperation : IDisposable
{
    private WindowsImpersonationContext ctx;

    public SystemOperation()
    {
        if (!WindowsIdentity.GetCurrent().IsSystem)
        {
            ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
        }
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool all)
    {
        if (ctx != null)
        {
            ctx.Undo();
        }
    }
}

Method #2:

   Microsoft.Sharepoint.SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        //Do an operation that requires retrieving across webs
    });

Best Answer

RunWithElevatedPrivileges provides two separate privledges. First is that it elevates the Windows identity of the user to the AppPool account, the second is that it also elevates the identity to the SharePoint\System account which is a built in security account that provides full control (in a SharePoint sense). The internal SharePoint account is used when you construct your SP Objects (like SPSite).

So basically it will depend on how you build your code and when you instatiate your objects that affect how the privledges work out.