Utility methods:
public static SPUserToken GetSystemToken(SPSite site) { bool cade = SPSecurity.CatchAccessDeniedException; SPSecurity.CatchAccessDeniedException = false; SPUserToken token = null; try { token = site.SystemAccount.UserToken; } catch (UnauthorizedAccessException) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite elevatedSite = new SPSite(site.ID)) { token = elevatedSite.SystemAccount.UserToken; } }); } finally { SPSecurity.CatchAccessDeniedException = cade; } return token; }
public static SPUserToken GetUserToken(SPSite site, SPWeb web, string userLoginName) { bool cade = SPSecurity.CatchAccessDeniedException; SPSecurity.CatchAccessDeniedException = false; SPUserToken token = null; try { token = web.GetUserToken(userLoginName); } catch (UnauthorizedAccessException) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite elevatedSite = new SPSite(site.ID)) { using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID)) { token = elevatedWeb.GetUserToken(userLoginName); } } }); } finally { SPSecurity.CatchAccessDeniedException = cade; } return token; }
Using the above methods:
SPSite contextSite = SPContext.Current.Site; SPWeb contextWeb = SPContext.Current.Web; SPUserToken authorUserToken = Utility.GetUserToken(contextSite, contextWeb, hfAuthorLoginName.Value); using (SPSite elevatedSite = new SPSite(contextSite.ID, authorUserToken)) { using (SPWeb elevatedWeb = elevatedSite.OpenWeb(contextWeb.ID)) { } }