A better way to impersonate in SharePoint (MOSS 2007/WSS 3.0)

Daniel Larson has a posting on his blog that explains running your SharePoint code in an elevated privileged environment. Here is a quick helper class.

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;

namespace SPLibrary
{
    /// <summary>A class for working with elevated privilege</summary>
    [CLSCompliant(false)]
    public static class SpSecurityHelper
    {
        /// <summary>Returns an elevated site</summary>
        /// <param name="theSite">
        /// The site that you want an elevated instance of.
        /// You must dispose of this object unless it is part of SPContext.Current.
        /// </param>
        /// <returns>An elevated site context.</returns>
        /// <remarks>Be sure to dispose of objects created from this method.&amp;t;/remarks>
        public static SPSite GetElevatedSite(SPSite theSite)
        {
            SPUserToken sysToken = GetSystemToken(theSite);
            return new SPSite(theSite.ID, sysToken);
        }

        /// <summary>Gets a UserToken for the system account.</summary>
        /// <param name="site"></param>
        /// <returns>A usertoken for the system account user./returns>
        /// <remarks>Use this token to impersonate the system account</remarks>
        public static SPUserToken GetSystemToken(SPSite site)
        {
            site.CatchAccessDeniedException = false;
            try {
                return site.SystemAccount.UserToken;
            }
            catch (UnauthorizedAccessException) {
                SPUserToken sysToken = null;

                // Only use runwithelevated to grab the system user token.
                SPSecurity.RunWithElevatedPrivileges(
                    delegate()
                    {
                        using (SPSite theSite = new SPSite(site.ID)) {
                            sysToken = theSite.SystemAccount.UserToken;
                        }
                    }
                );
                return sysToken;
            }
        }
    }
}
Bookmark and Share
Leave a comment

1 Comments.

  1. Hello! In my blog I’ve demonstrated the similar implementation, but which restores the old value of site.CatchAccessDeniedException when method is ending. It’s here http://dotnetfollower.com/wordpress/2011/03/sharepoint-how-to-get-systemaccount-token/

Leave a Reply


[ Ctrl + Enter ]

Performance Optimization WordPress Plugins by W3 EDGE