Monday, December 8, 2008

Impersonating another user to run code

Scenario:
You want to impersonate other user's identity to run some code.
Solution:
'SPSite' support a special constructor , which excepts the user context token.
Code:

SPUser user = SPContext.Current.Web.SiteUsers[@"domain\username"];

using(SPSite oSiteCollection = new SPSite("http://localhost/", user.UserToken)){
//Code goes here
}
Remarks:
SPSite objects that are created with a user token run in the context of the specified user. The current code must have the SharePointPermission.Impersonate code access security (CAS) permission. It is not possible to change the user context of an SPSite object once it has been created. Switching users requires creating a new SPSite object.

Pluggable membership and role providers that are making a request must match the provider on the resource side.

Use the UserToken property to get the user token that is associated with any SPUser object, not just the current user. If the requested user is not the current user, Windows SharePoint Services first tries to retrieve the cached user token from the database. If no token is cached, or if the cached token is stale, Windows SharePoint Services rebuilds the token from the security ID (SID) of the user, and gets the group membership information using the authorization object model (see Users, Groups, and Authorization).

Article:http://msdn.microsoft.com/en-us/library/ms436101.aspx

0 comments: