Thursday, December 03, 2009

SharePoint Impersonation by SPUser

The SPUser class has a UserToken property that can be passing into the SPSite constructor to impersonate that particular user:
        SPSite contextSite = SPContext.Current.Site;
        SPUser user = contextSite.SystemAccount;
        using (SPSite site = new SPSite(contextSite.ID, user.UserToken))
        {
            using (SPWeb web = site.OpenWeb())
            {
                // Do stuff
            }
        }
Above code snippet impersonates the system account to open a SPSite which is equivalent to:
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Do stuff
                }
            }
        });