There are times when developing custom web parts and other SharePoint solutions, you need to impersonate a user and view SharePoint from within their context. Impersonating a user in SharePoint requires a few things:
- the account that the web or console application users that has privileges to impersonate other users (typically this would be the system account)
- specific users’ user tokens
Step 1: Log in as the system account, or get a handle to the system account in your code
string siteURL = "http://mysite/";
// we just need to get a handle to the site for us
// to get the system account user token
SPSite parentSite = new SPSite(siteURL);
SPUserToken systemToken = parentSite.SystemAccount.UserToken;
using (SPSite site = new SPSite(siteURL, systemToken))
{
using (SPWeb web = site.OpenWeb())
{
// Add code to initiate impersonation
}
}
Step 2: Before you impersonate, get the user token of the user you are switching to. For example:
// Get the current user's user token
SPUserToken userToken = web.AllUsers[user].UserToken;
// Create an SPSite object in the context of the user
SPSite site = new SPSite(siteURL, userToken)
SPWeb web = site.OpenWeb();
// Add code to be executed in context of impersonation
Complete code follows:
private static void ImpersonateUser()
{
string siteURL = "http://mysite/";
SPSite parentSite = new SPSite(siteURL);
SPUserToken systemToken = parentSite.SystemAccount.UserToken;
using (SPSite site = new SPSite(siteURL, systemToken))
{
using (SPWeb web = site.OpenWeb())
{
OpenUserContext(web, siteURL, "DOMAIN/JoeDoe");
}
}
}
private static void OpenUserContext(SPWeb web, string siteURL, string user)
{
SPUserToken userToken = web.AllUsers[user].UserToken;
SPSite impSite = new SPSite(siteURL, userToken);
SPWeb impWeb = impSite.OpenWeb();
// Do something as impersonated user
Console.WriteLine("Currently logged in as: " + impWeb.CurrentUser.ToString() + "(" + impWeb.CurrentUser.Name + ")");
}