Wednesday, February 15, 2012

Best practice to impersonate users for SharePoint API calls

We have a requirement to develop a event receiver to copy list items into another list. During the design, I’ve asked developer not only copy the list items, but also keep the created by and modified by same as source list so that the audit history will reflect the active users.

The way to implement is to impersonate the call. Here is simple example.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Impersonate
            string siteStr = "http://sbx08/sites/Harry/";

            using (SPSite site = new SPSite(siteStr))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Impersonate to user “an/harryc”
                    SPUserToken utoken = web.AllUsers["na/harryc"].UserToken;

                // Open site as that user
                    using (SPSite newSite = new SPSite(siteStr, utoken))
                    {
                        using (SPWeb newWeb = newSite.OpenWeb())
                        {
                            Console.WriteLine(newWeb.CurrentUser.ToString());

                            // Impersonate code to interact with SharePoint
                        }
                    }

                }
            }
        }
    }
}


If users do not have the permission on the destination list, we have to use run with elevated privileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
    {
        using (SPWeb elevatedWeb = site.OpenWeb(webId))
        {
            //Your code here
        }
    }
});


All these two are very common and I just want to keep the sample in my blog to train my new developers.

No comments:

Post a Comment