Search code examples
sharepointsharepoint-2010web-partselevated-privileges

Sharepoint query with elevated privileges


A Webpart needs to access a Sharepoint List (read mode). If the user is admin, there isn't problem (works as espected), but if the user hasn't permissions to access, I must use "RunWithElevatedPrivileges" method.

The problem is that seems that the query don't return the correct results. What I'm missing?

        SPList demoList = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            SPSite oSite = SPControl.GetContextSite(HttpContext.Current); // ADDED
            SPWeb oWeb = oSite.OpenWeb();                                 // ADDED
            demoList = oWeb.Lists["nameList"];
        });
        // demoList has 3 Elements (admin and no admin user) OK

        SPListItemCollection collListItems = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            SPQuery oQuery = new SPQuery() { Query = "<OrderBy><FieldRef Name='Date' Ascending='False' /></OrderBy>" };
            collListItems = demoList.GetItems(oQuery);
        });

        // 
        //IF ADMIN
        //collListItems.Count ==>3

        //IF NO ADMIN 
        //collListItems.Count ==>0

Solution

  • You need to create new object with elevated privieges.

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        SPSite oSite = new SPSite(SPContext.Current.Site.ID); 
        SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID);                                 
        demoList = oWeb.Lists["nameList"];
    });
    

    Also, you should dispose of the newly created objects and there is no need for two delegates.

    SPSecurity.RunWithElevatedPrivileges(delegate {
        using (SPSite oSite =new SPSite(SPContext.Current.Site.ID))
        using (SPWeb oWeb = oSite.OpenWeb()) {
            var demoList = oWeb.Lists["nameList"];
            SPQuery oQuery = new SPQuery
                                { Query = "<OrderBy><FieldRef Name='Date' Ascending='False' /></OrderBy>" };
            SPListItemCollection collListItems = demoList.GetItems(oQuery);
    
            //IF ADMIN
            //collListItems.Count ==>3
    
            //IF NO ADMIN 
            //collListItems.Count ==>0
        }
    });