Tuesday, June 2, 2009

Impersonating User Identity

Scenario:
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.

Solution:
This is a very good alternate to RunWithElevatedPrivileges.

Code:

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
}
}
Article:http://msdn.microsoft.com/en-us/magazine/cc163287.aspx

1 comments:

Anonymous,  November 29, 2010 at 2:02 PM  

Minor update on line #1:

SPSite siteCollection = SPContext.Current.Site;
...
...

-Am