2 minute read

The last time I have been receiving questions about using SPSecurity.RunWithElevatedPrivileges in a SharePoint webpart. This made me think and I thought by myself lets write a short post with some examples about this subject.

When you want to build a webpart that will be used by anonymous or read only users you often have to use RunWithElevatedPriviledges because a lot of objects in a SharePoint site require more rights. If you use RunWithElevatedPriviledges you will run a particular action under a account that has more rights in SharePoint.

I hear you asking under what account do we run this particular code then? The answer is the application pool account of your web application.

Now we know that we can write some examples to see what will work. Let’s begin with an example how you should not use RunWithElevatedPriviledges.

 SPWeb web = SPContext.Current.Web;

 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
    SPList list = web.Lists["Test"];
 });

In this example we get the current web object from the SPContext. This means we have got a web object that runs under the account that we are logged in with. After we have got the web object we use RunWithElevatedPriviledges because read only users can not access the list.

If we would run this code in a webpart we will see an access denied message, all because we use a web object that is retrieved with our current context.

Let’s take a look at an example how you could do it the right way (this is the way I mostly use RunWithElevatedPriviledges):

Guid webID = SPContext.Current.Web.ID;
 Guid siteID = SPContext.Current.Site.ID;

 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
    using (SPSite site = new SPSite(siteID))
    {
       using(SPWeb web = site.AllWebs[webID])
       {
          SPList list = web.Lists["Test"];
       }
    }
 });

In this example you can see that we first retrieve the ids of the site collection and the web so that we know which site object and web object we want to work with.

We then use RunWithElevatedPriviledges and retrieve the SPSite and SPWeb within the RunWithElevatedPriviledges. These objects will then run under the account of the application pool.

I hope this post will you guys out there and please fill free to leave comments.