Thursday, November 6, 2008

Using ElevatedPrivileges in SharePoint Web Parts

Yesterday I found myself into a situation in which a custom web part couldn't reach a particular SharePoint list.

Situation:

Due to the current security schema, none user should have more than read access to the Root Collection Site and at the same time for centralizing purposes, a list was created on that Collection Site.
A particular web part located several levels down the collection needed access to that list, but as no common user had the appropiate permisison level it was returning the famous "Access Denied" screen.

Solution:

I needed to elevate the privileges on the web part at the time of accessing the list to solve the problem.

Guid RootSiteID = SPContext.Current.Site.ID;
Guid RootWebID = SPContext.Current.Site.RootWeb.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(RootSiteID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(RootWebID))
{
rootList = ElevatedSite.Lists[_strSPListName];
}
}
});


Doing so, I could get the SPList rootList out of the site collection.

One important thing to remember is that you need to create a new SPSite and SPWeb within the RunWithElevatedPrivileges and not take them from the context in order to avoid using the current user "low privileges".

No comments: