Thursday, October 22, 2009

SharePoint Progamming 101 - Impersonation

Many times you want to make sure that your code runs no mater what permissions the current user has. There are two easy ways that you can accomplish this in SharePoint. Both of the techniques do the same thing, execute code with the permissions of the application pool the site is running under.  You must create a new spweb object from a url after impersonating the application pool.

Method 1
            //Impersonate the pool
            WindowsImpersonationContext ctx = null;
            ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);          

            SPSite site = new SPSite("http://mysteurl");
            SPWeb web = site.OpenWeb();
            try
            {
                //All of this code will run with elevated privileges   

            }
            catch (Exception ex)
            {}
            finally
            {
                    web.Dispose();
                    //make sure you revert to normal
                    ctx.Undo();
             }

Method 2
            //Impersonate the pool
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite("http://mysteurl"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                         //All of this code will run with elevated privileges     
                    }
                }
           });

No comments:

Post a Comment