Monday, April 8, 2013

Elevation of Privilege Best Practice

  • Remember that All Elevated Objects Must Remain Inside a RunWithElevatedPrivileges Block.
  •  All Elevated object which created in side the RunWithElevatedPrivileges not  returned to outside of the RunWithElevatedPrivileges block. 
  • If the SPListItem object is passed outside of the RunWithElevatedPrivileges block, it retains its underlying SPRequest object and continues to be elevated. Code that expects to be running under the current user's credentials will have privilege elevation problems if it uses this SPListItem object.



example 

Do not Use RunWithElevatedPrivileges like that


SPSecurity.RunWithElevatedPrivileges(delegate() {

   SPSite osite = SPContext.Current.Site;   

   SPWeb oweb = SPContext.Current.Web;  

// here you need to use oweb object as system user.
      //oweb.CurrentUser.LoginName
 

        });//Close "SPSecurity.RunWithElevatedPrivileges" block




always use using block with SPSite ,SPWeb   like that



Guid GwebID = SPContext.Current.Web.ID;
Guid GsiteID = SPContext.Current.Site.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(GsiteID))
    {
try
{
        site.AllowUnsafeUpdates = true;
        using (SPWeb web = site.OpenWeb(GwebID))
        {
            web.AllowUnsafeUpdates = true;
          // Perform administrative actions
        }

}
catch
{
   // Handle or re-throw an exception.
}
finally
{
   site.AllowUnsafeUpdates = false;
}
         
    }
});


Reference :
http://msdn.microsoft.com/en-us/library/gg552614.aspx#bestpractice_elevpriv



No comments:

Post a Comment