Pages

Search This Blog

Monday, March 14, 2011

Event Impersonation in Sharepoint 2010

In earlier versions of SharePoint Foundation, events that occurred when a request was being processed ran in the context of the user whose action raised the event. Generally, this was acceptable; furthermore, if this created a problem, a developer could either revert to using the system account context, or create a new SPSite object for use with a particular user.

In some scenarios, for example, when an active workflow has code that is running with elevated privileges, the code runs in the context of the system account. But in this scenario, when event receiver code needs to run with the credentials of the originating user, SharePoint Foundation 2010 added a new property called “OriginatingUserToken” on the “SPEventPropertiesBase” class that returns the ID of the originating user. Event code should check for this user by ID, and, optionally, perform behaviors that can potentially cause unexpected effects by using an impersonated site collection with the token of that originating user.

public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           SPUserToken objSPUserToken = properties.OriginatingUserToken;
           if (objSPUserToken != null)
           {
               using (SPSite objSPSite = new SPSite(properties.SiteId, objSPUserToken))
               {
                   using (SPWeb objSPWeb = objSPSite.OpenWeb())
                   {
                       //You can perform user context specific changes here...
                   }
               }
           }

       }

1 comment: