A few days ago, I wrote event handler code that runs in the security context of the logged in user. SharePoint security model makes it easy to programmatically execute code within the current user context But there were some situations when the code needs to be executed with permissions greater than that of the current user (like instantiating a site collection or enumerating list permissions ).
In such situations, the code needs to be executed with elevated permission level or under the context of user with higher permissions i.e. Impersonation.
As the MSDN documentation says, SPSecurity.RunWithElevatedPrivelege “Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.”
In my experience with Using SPSecurity.RunWithElevatedPrieveleges, there are too much tricks that you should take care of.
For Instance : You must create the new SPSite objects inside the delegate because SPSite objects created outside do not have Full Control even when referenced inside the delegate. Use the using keyword to ensure that the object is disposed in the delegate. The next example shows this. SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(web.Site.ID))
{ // Perform elevated actions here
}
});
The problem is that the SPWeb object from the current context is initialized using the current user’s credentials, so even though we run the code snippet with elevated privileges the actual access to the file is still restricted. To resolve this we have to create a new SPSite/SPWeb object within the elevated code, where we run in the context of the elevated user. Then we can perform the restricted action. Since the SPSite/SPWeb objects are created explicitly we have to also dispose of them.
There’s too much overhead, too much chances of introducing obscure bugs, too much potential abuse when it comes to using SPSecurity.RunWithElevatedPrievelges.
That’s why I’d recommend to use SPUserToken to impersonate the SYSTEM and use elevated privileges.
Fortunately, the SystemAccount SPUser is a property of any SPSite object. So instead of using SPSecurity.RunWithElevatedPrivelege, you can use the following code to perform elevated actions:
SPUserToken systemAccountToken = SPContext.Current.Site.SystemAccount.UserToken;
using(SPSite mySite = new SPSite(SPContext.Current.Site.ID, systemAccountToken))
{
using (SPWeb myWeb = mySite.OpenWeb(SPContext.Current.Web.ID))
{
// Perform elevated actions here
}
}