mylifeinaminute.com

Archive for July 9th, 2008

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

by liquidpooled on Jul.09, 2008, under .NET, Microsoft, Office, Sharepoint Server, Visual Studio 2005, Visual Studio 2008, Windows SharePoint Services

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.</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 lolcatKiller = new SPSite(site.ID)) {
                            sysToken = lolcatKiller.SystemAccount.UserToken;
                        }
                    }
                );
                return sysToken;
            }
        }
    }
}
Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...