No RunWithElevatedPriviliges in Event Handlers

No RunWithElevatedPriviliges in Event Handlers

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 -

http://blogs.msdn.com/varun_malhotra/archive/2008/07/21/why-does-runwithelevatedpriviliges-not-work-in-event-handlers.aspx

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:
[code lang="csharp"]
SPUser user = web.AllUsers["kci\sp_prodapppool"];

SPUserToken token = user.UserToken;

SPSite kciSite = new SPSite(site.Url, token);

SPWeb kciWeb = kciSite.OpenWeb();
[/code]
Have fun coding! :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">