Implement and debug code that executes in an alternative security context

When working from code you eventually run into situations where the current user’s rights are not sufficient. To overcome these situations SharePoint allows some methods to run your code in the context of different users and different privilege levels.

To impersonate a user, you can pass the user’s token when you create an SPSite. This looks like this:

SPUser someUser; //acquire the user somehow
using (SPSite site = new SPSite(“my site’s url”, someUser.UserToken))
//do stuff

That’s fairly easy, now the code will have the same privileges as the user being impersonated. Running code that uses the system account user works exactly the same way. The only difference is that you need to acquire the user token of the system account user. This can be gathered from the SPContext class, the full path is SPContext.Current.Site.SystemAccount.UserToken.

Finally you can run code with full control a little bit differently. You need to use the SPSecurity.RunWithElevatedPrivileges method. This method expects a parameterless void delegate, and it’ll execute the code given in a full control context. If you’d do any write operations you should call SPUtility.ValidateFromDigest (especially if you invoke the delegate from an HTTP GET). The other way is to play around with AllowUnsafeUpdates on web and site objects, but validating the form digest in the entry point is much easier and more convenient.

When you invoke the RunWithElevatedPrivileges method it’ll run in a different context and you can only access the objects created in the delegate method with elevated permissions. Previously created objects are accessed with the original permissions. Also the SPContext site and webs won’t magically become elevated, you should recreate them as your own objects if you’d like to access them, by using their identifiers.

You should note that the RunWithElevatedPrivileges method does not work in sandboxed solutions.