Search This Blog

Saturday, March 19, 2011

Change user context programatically in SharePoint.

Sometimes we need to execute some piece of code with the context of particular user account.There is RunWithElevatedPrevilages, which allows to execute the code with administrative rights (system account context) but what if piece of code required to execute with the context of XYZ user.

SharePoint supports the SPUserToken class which is used to get the token of the user and SPSite constructor use the SPUserToken to open the site object in the context of the user.Following examples will help you to understand it.

***********************************************************************
String SiteURL = "Http://localhost";

SPSite objSite1 = new SPSite(SiteURL);

SPUserToken objSPUserToken = objSite.SystemAccount.UserToken;

using (SPSite objSite2 = new SPSite(SiteURL, objSPUserToken))
{
using (SPWeb objSPWeb = objSite2.OpenWeb())
{
String CurrentUser = objSPWeb.CurrentUser.DisplayName;
}
}

************************************************************************
SPUserToken objSPUserToken = Web.AllUsers[user].UserToken;
using (SPSite objSPSite = new SPSite(siteStr, objSPUserToken))
{
using(SPWeb objSPWeb = objSPSite.OpenWeb())
{
String CurrentUser = objSPWeb.CurrentUser.DisplayName;
}
}

Hope the above examples will help you to execute the piece of code with context of perticular user.

I got the above details from the "donabel"
http://blackninjasoftware.com/2009/04/09/how-to-programmatically-impersonate-users-in-sharepoint/.

No comments:

Post a Comment