RunWithElevatedPrivileges in SharePoint 2010/2013

This SharePoint tutorial explains, what is RunWithElevatedPrivileges and how to use RunWithElevatedPrivileges in SharePoint 2010/2013 with SharePoint server-side object model code.

SPSecurity.RunWithElevatedPrivileges method

SPSecurity.RunWithElevatedPrivileges method executes the specified method with Full Control rights even if the user does not otherwise have Full Control.

  • Suppose you have written a piece of code that will add an item to a SharePoint list. But suppose a user has only read access to the site then s/he will get the access denied error when try to execute the code. But still you can run the code by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
  • The SPSecurity class exposes a method called RunWithElevatedPrivileges, which gives you an option to elevate the privilege to the application pool identity under which your code is executing.

Syntax:

SPSecurity.RunWithElevatedPrivileges(
delegate()
{
// Code will go where
}
);
  • Elevated privilege can be used to bypass or work with security.

Here are some points to follow while working with RunWithElevatedPrivileges in SharePoint.

  • Avoid using SPSecurity.RunWithElevatedPrivileges to access the SharePoint object model. Instead, use SPUserToken to impersonate SPSite with a specific account, as shown previously.
  • If you do use SPSecurity.RunWithElevatedPrivileges, dispose of all objects in the delegate. Do not pass SharePoint objects out of the RunWithElevatedPrivileges method.
  • Only use SPSecurity.RunWithElevatedPrivileges to make network calls under the application pool identity. Don’t use it for the elevation of the privilege of SharePoint objects.
  • If you run code with elevated privileges and you create new objects, such as list items within a list, the user automatically assigned as author or editor is SHAREPOINT\system.

SPSecurity.RunWithElevatedPrivileges Example

Here is an example that will add an item to a SharePoint list where we have used RunWithElevatedPrivileges.

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite myTopSite = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb myTopWeb = myTopSite.OpenWeb(SPContext.Current.Site.RootWeb.ID))
{
myTopWeb.AllowUnsafeUpdates = true;

SPList listMyList = myTopWeb.Lists.TryGetList(“MyList”);

SPListItem newItem = listMyList.Items.Add();
newItem[“Title”] = “Item 1”;
newItem[“Description”] = “This is item 1”;
newItem.Update();
myTopWeb.AllowUnsafeUpdates = false;
}
}
}
});

}
catch (Exception ex)
{

}

You may like following SharePoint server object model examples:

Hope this SharePoint tutorial helps to learn what is RunWithElevatedPrivileges in SharePoint? How we can use RunWithElevatedPrivileges in SharePoint 2010/2013 with SharePoint server side objct model code. We also saw one example on RunWithElevatedPrivileges in SharePoint.

>