Elevated Code for SharePoint - RunWithElevatedPrivileges


By:   |   Updated: 2010-06-08   |   Comments   |   Related: > SharePoint Configuration


Problem

When developing for SharePoint you may find your code does not execute due to the users permission levels.

Solution

This is a common problem when developing in SharePoint. Your code works perfectly during development as your mostly likely developing as the local admin on your "Development" SharePoint server, right? However, when you try running your code as a normal SharePoint user it doesn't run correctly and throws a permissions error.

The solution is to make sure you elevate your code ( SPSecurity.RunWithElevatedPrivileges(..delegate here..) ) correctly where needed. You may be doing this already but still getting the error as there is a gotcha, your objects need to be instantiated inside the delegate.

This works:

Guid webGuid = web.ID; 
Guid siteGuid = web.Site.ID; 
string fileURL = item.File.Url;

SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
  using (SPSite site = new SPSite(siteGuid))
  { 
     using (SPWeb ElevWeb = site.OpenWeb(webGuid)) 
     { 
        SPFile ElevFile = ElevWeb.GetFile(fileURL); 
        // do something with ElevFile 
     } 
  } 
  
}); 

This fails, because the SPFile object is instantiated outside of the delegate:

Guid webGuid = web.ID; 
Guid siteGuid = web.Site.ID; 
SPFile ElevFile = item.File; 

SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
  using (SPSite site = new SPSite(siteGuid))
  { 
     using (SPWeb ElevWeb = site.OpenWeb(webGuid)) 
     { 
        // do something with ElevFile - breaks
     } 
  } 
  
}); 

There are 2 big things to know about this:

  • It runs using the App Pool account, so you must ensure that the App Pool account is a member of a site collection group with sufficient perms to to add/edit/delete or whatever your code is trying to do. If not, the code will quietly break without popping an exception
  • All objects used within the delegate must be instantiated within the delegate, otherwise the elevation will fail. You can safely call scalars instantiated outside of the delegate, but not object variables like site or web.
Next Steps


Last Updated: 2010-06-08


get scripts

next tip button



About the author





Comments For This Article





download





Recommended Reading

Best Practices for SharePoint Content Databases in SQL Server

Configure SharePoint Forms Based Authentication to use LDAP

Creating Web Applications, Site Collections and Sites in SharePoint 2010

Configuring Alternate Access Mapping in SharePoint 2010

Opening PDF Files in a Browser from a SharePoint 2010 library








get free sql tips
agree to terms