Friday, August 13, 2010

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context 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 simply write code within an inline delegate.

The signature looks like the following:

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


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that 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, but must instead create a new SPSite reference to switch user contexts. The following code 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();
}
}
);

No comments:

Post a Comment