Wednesday 27 July 2011

SharePoint - Elevated Privileges


When developing using the SharePoint object model, certain operations has to be run with elevated privileges. For instance, setting information into the property bag of a site needs to be done with elevated privileges. This post shows how this is done, and also includes a helper method for making it easier and shorter to do this.
There is a method called SPSecurity.RunWithElevatedPrivileges in the object model that takes a delegate as argument. The delegate is then run with more permissions. An important note regarding this: You must not use old references to SPWeb or SPSite instances inside your delegate, since they are “contaminated” with lower permissions. What you have to do is to create new SPSite and SPWeb instances using the Ids of the sites and webs you already have a reference to, like this
SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
    using (SPSite site = new SPSite(SPContext.Current.Site.ID)) 
    { 
        using (SPWeb elevatedWeb = site.OpenWeb(webId)) 
        { 
            //Your code here 
        } 
    } 
});
If you need to do these kind of operations in several locations, this is a lot of repeating code to include. A colleague of mine made a small helper method that does the setup for elevated privileges for you. Here’s the short code snippet:

private delegate void CodeToRunElevated(SPWeb elevatedWeb);
private static void RunElevated(Guid webId, CodeToRunElevated secureCode)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite site = new SPSite(SPContext.Current.Site.ID))
        {
            using (SPWeb elevatedWeb = site.OpenWeb(webId))
            {
               secureCode(elevatedWeb);
            }
        }
    });
}
To invoke this, you call on the method with the Id of your web as one argument, and a delegate taking an SPWeb as the other. When the method is invoked, the SPWeb argument will be “uncontaminated” and pushed to elevated privileges. This example sets the name, title, and description of a site.

RunElevated(web.ID, delegate(SPWeb elevatedWeb)
{
    elevatedWeb.Name = siteTitle;
    elevatedWeb.Title = siteTitle;
    elevatedWeb.Description = siteDescription;
    elevatedWeb.Update();
});