Tuesday, June 2, 2009

Impersonating User Identity

You might want to impersonate a specific WSS user identity before creating a new object so that WSS user is recognized as the owner of the new object.
In order to impersonate a WSS user identity, you must first create an SPUserToken object. You can do this by accessing the UserToken property of an SPUser object. Once you have the SPUserToken object, you can use it to create a new SPSite object using an overloaded version of the SPSite class constructor.

This is a very good alternate to RunWithElevatedPrivileges.


SPSite siteCollection = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;

// get SPUser object and acquire token
SPUser targetUser = site.SiteUsers[@"LITWAREINC\BrianC"];
SPUserToken token = targetUser.UserToken;

// create new SPSite and SPWeb object to impersonate user
using (SPSite impersonatedSiteCollection =
new SPSite(siteCollection.ID, token)) {
using (SPWeb impersonatedSite =
impersonatedSiteCollection.OpenWeb(site.ID)) {
// WSS identity switched to impersonate BrianC
// Windows identity does not change


Anonymous,  November 29, 2010 at 2:02 PM  

Minor update on line #1:

SPSite siteCollection = SPContext.Current.Site;