Elevation of Privilege Best Practice

Monday, April 8, 2013

  • 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.


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.

        });//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;

    using (SPSite site = new SPSite(GsiteID))
        site.AllowUnsafeUpdates = true;
        using (SPWeb web = site.OpenWeb(GwebID))
            web.AllowUnsafeUpdates = true;
          // Perform administrative actions

   // Handle or re-throw an exception.
   site.AllowUnsafeUpdates = false;

Reference :

share this post
Share to Facebook Share to Twitter Share to Google+ Share to Stumble Upon Share to Evernote Share to Blogger Share to Email Share to Yahoo Messenger More...