Feb 052007
 

SPSecurity provides a static method RunWithElevatedPrivileges that allows code to execute as the System Account (SHAREPOINTsystem). This allows code to run in an escalated security context in order to perform actions as the system. This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple, you can either create a delegate to a public void method or you can simply write code within an inline delegate. The signature looks like this:

SPSecurity.RunWithElevatedPrivileges(  delegate(){
  // Code runs as the "SharePointsystem" user
});

Code within the delegate runs under the Windows security principal “SHAREPOINTsystem”. However, if you were to use code similar to the following, you will notice a bug in your code that seems like the security context is not switched:

// Bad code example:
SPSecurity.RunWithElevatedPrivileges(  delegate() { 
  SPListItem record = visitorList.Items.Add(); // still the calling user 
  record["User"] = SPContext.Current.Web.CurrentUser;  
  record.Update();
});

In order to modify WSS content under the System credentials, you will need to create a new SPSite site collection, which generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created. You must instead to create a new SPSite reference to switch user contexts. The following code snippet uses the system credentials to add a list item using the profile data of the current web user:

SPSecurity.RunWithElevatedPrivileges(  delegate() { 
  using (SPSite site = new SPSite(web.Site.ID)) {
      using (SPWeb web2 = site.OpenWeb()) {
          SPList theList = web2.Lists["visitors"];
          SPListItem record = theList.Items.Add();
          record["User"] = SPContext.Current.Web.CurrentUser;
          record.Update();
}});

Code running in the escalated privilege should use a new SPSite object for code running as the system, and should use the SPContext.Current in order to access the actual calling user’s identity.

*Create a new SPSite reference while impersonating to perform actions in the impersonated context.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>