Thursday, December 22, 2011

SPSecurity.RunWithElevatedPrivileges

The ideal way to Elevate Privileges:

(Code written on the run - Check for build errors)

Guid SiteID = SpWeb.Current.Site.ID;
Guid WebID = SPWeb.Current.Web.ID;

SpSecurity.RunWithElevatedPrivileges(delegate(){

using (SPSite oSite = new SPSite(sSiteID))
{
              using (SPWeb oWeb = oSite.OpenWeb(WebID))
               {
                             //Logic
                }
}
});

One thing to be kept in mind while implementing such logic is that any SP Object with is created outside of the RWEP belongs to that particular context and when that SP Object is sent inside the RWEP, the elevation is lost.

For Example, if I need to use a list within the RWEP, then I should follow these:

DoSomethingWithTheList(SPList tempList)
{
    Guid SiteID = SpWeb.Current.Site.ID;
    Guid WebID = SPWeb.Current.Web.ID;
    string sListName = tempList.Title;

    SpSecurity.RunWithElevatedPrivileges(delegate()  
   {
        using (SPSite oSite = new SPSite(sSiteID))
       {
            using (SPWeb oWeb = oSite.OpenWeb(WebID))
           {
                 SPList oList = oWeb.Lists.TryGetList(sListName);
                 //Logic
           }
       }
   });
}

1 comment:

  1. Thanks for the post. Below post will helps us on how to use and avoid access denied issues while using RunwithElevatedPrivileges best practice
    http://sharepointquicksolutions.blogspot.in/2012/11/all-ways-of-runwithelevatedprivileges.html

    Thanks
    Sasi kumar Reddy

    ReplyDelete