There are some situations where in we need to change the executing code identity. Whenever code runs in WSS and in SharePoint, code actually executes in the logged in user’s identity. However this is not true in terms of workflow or the event handler where user does not play any identity role.
In these cases it is the system account that is considered as logged in user and all tasks are performed on that credential.
If we want to change the logged in user identity and make the code run on some other user’s identity at that time we can impersonate the identity of logged in user.
For example, in event handler or in workflow you want to change the user’s identity for executing code, you can do so with the help of SPUserToken class.
All we need to do is first take a reference of SPUser by getting user from SiteUsers method, and then pass the user token while initiating SPSite object. Once you do this, your code will run under specified user.
Before showing up the example, I would like to note here is that this process is different than RunWithElevatedPrivileges because this change of user token does not change the windows logged in user identity, it’s the User identity with respect to the WSS that changes. And the other important point to bring out here is that to perform the above mentioned code, your code first must run under RunWithElevatedPrivileges to user SPUserToken and change user.
SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = SPContext.Current.Web;
SPUser objUser = objWeb.SiteUsers[@"domain\user"];
SPUserToken usertoken = objUser.UserToken;
using (SPSite SiteColl =
new SPSite(objSite.ID, usertoken)) {
using (SPWeb web =
SiteColl.OpenWeb(objWeb.ID)) {
}
}
That is it. you have just changed the User token while executing the code.
2 comments:
http://aviralchawda.blogspot.com/2011/11/impersonate-user-in-sharepoint-net.html
Great blog, thanks!
Just wanted to point out of course this only applies to Farm Solutions. Sandboxed solutions are restricted to running all code with the rights of the logged in user.
Post a Comment