Friday, June 27, 2008

Running with Elevated Privileges

SharePoint 2007 offers a nice and easy way for elevating your permissions using delegates.

The main catch is to remember that you cannot use any of the Context objects such as SPContext to directly retrieve your objects.  But this can be easily overcome by using the ID attribute of the Site object in the Context to retrieve a copy of the site.

 

        protected void MyMethod()

        {

            SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated(MyElevatedMethod);

            SPSecurity.RunWithElevatedPrivileges(elevatedMethod);

        }

 

        private void MyElevatedMethod()

        {

            // do not use the Context object directly since it uses the logged in credentials

            // instead create a new object using the site id retrieved from the Context

            using (SPSite site = new SPSite(SPContext.Current.Site.ID))

            {

                // do your stuff here

            }

        }

0 comments: