Pages

Search This Blog

Monday, April 11, 2011

Impersonation in Sharepoint

In a scenario I have to implement the impersonation. In this, user X has to impersonate user Y, so that the user X can access all the functionalities of the user Y. For this implementation, we need to have the user token of the user Y, which can be used when X impersonates user Y.
To achieve this, follow the following code snippet

STEP 1: Retrieve the SPUserToken of the user Y.
SPUserToken UserYtoken;
string URL = SPContext.Current.Site.Url;
using (SPSite objSite = new SPSite(URL))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
SPUser UserY = objWeb.EnsureUser(“@Domain\\UserName”);
UserYtoken = UserY.UserToken;
}
}
STEP 2: User X can impersonate user Y using the following code snippet.
using (SPSite objSite = new SPSite(URL, UserYtoken))
{
using (SPWeb objWeb = objSite.RootWeb)
{
//Now the current context is of User Y and user X can access the contents that User Y can
}
}
Happy Coding..!!!

No comments:

Post a Comment