Friday, July 9, 2010

How to impersonate user identity in WSS

Hi All,

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:

Aviral Chawda: SharePoint Developer said...

http://aviralchawda.blogspot.com/2011/11/impersonate-user-in-sharepoint-net.html

Darren said...

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.




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com