In SharePoint custom development activities, we have to impersonate the user to view SharePoint contents. To impersonate user in SharePoint we need to have the account that having privileges (generally in Run with elevated privileges “System Account” will be used) or user tokens.
To handle with System Account, we can use following code block,
SPSite parentSite = new SPSite(siteURL);
SPUserToken systemToken = parentSite.SystemAccount.UserToken;
using (SPSite site = new SPSite(siteURL, systemToken))
using (SPWeb web = site.OpenWeb())
// Code to be run
We can impersonate the by using following code by getting the user token of the user to switch as shown the code below,
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 here.
To run this code, we need to run the code System account