No RunWithElevatedPriviliges in Event Handlers

23 01 2009

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:

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! 🙂

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: