I’ve just been working on a simple event handler to restrict users from deleting documents unless they are in a particular SharePoint group. This required me to access the SPWeb.Users function to iterate through the users.
If the user was not an administrator on the SharePoint site the code bombed out as the user doesn’t have permission to access the list of users on the site, this is happening because an event handler runs under the user who is performing the operation.
I decided to use the RunWithElevatedPriviliges to impersonate the Application Pool but this didn’t work either and as it turns out you cannot use ‘RunWithElevatedPriviliges’ in SharePoint event handlers!
In Trailblazer’s blog post -
he describes how you cannot use this method of impersonation nor the standard Windows.Impersonate() function in event handlers. The only workaround is to use Explicit Impersonation.
Explicit impersonation means creating an SPUser object for the administrator, getting the SPToken of the user and then using this token to open the SPSite.
See the code example below:
SPUser user = web.AllUsers["kci\sp_prodapppool"];
SPUserToken token = user.UserToken;
SPSite kciSite = new SPSite(site.Url, token);
SPWeb kciWeb = kciSite.OpenWeb();
Have fun coding!