Tuesday, 17 February 2015

SharePoint RunWithElevatedPrivileges

What is Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges?

Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.

This method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.


  • Using SharePoint context with an unauthenticated user does not actually elevate privileges:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // do something with SPContext.Current.Web
    // fails with a HandleAccessDenied Exception
    // because SPContext is loaded with the site,
    // not within this delegate block.
});

  • So to get actual elevated privileges, you have to reload the context:


SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(this.Page.Request.Url.ToString()))
    {
        using (SPWeb thisWeb = site.OpenWeb())
        {
            // do something with thisWeb
        }
    }


});

No comments:

Post a Comment