Tuesday, 24 June 2014

SharePoint 2010: Why does my RunWithElevatedPrivileges not pick up the context of the Application Pool user?

It is important to remember that RunWithElevatedPrivileges requires its own SPWeb. If you reuse a existing SPWeb, you won't run elevated, but with the initial context.

For Example, the following function is intended to perform some actions on the sub sites for the given site. The access requires elevated permissions:

This function will not work:

private void DoStuff (SPWeb web)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
foreach (SPWeb w in web.Webs)
// Still running under logged in user credential
}
});
}

but this will:

private void DoStuffProperly(SPWeb web)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(web.Url))
{
using (SPWeb w = site.OpenWeb())
{
// Running under the application pool credential
}
}
});
}

No comments:

Post a comment