Wednesday, March 5, 2008

RunWithElevatedPrivelages

I'm sure many many people have tried building web parts that need to perform operations to which the currently logged user potentially doesnt have security clearance for.

I'm one of those persons.

The easiest most effective way to accomplish this is to use the SPSecurity.RunWithElevatedPrivelages(delegate()) method.

When i started looking into this i found several sources indicating that the correct way of using this method is as follows:


SPWeb objWeb = SPControl.GetContextWeb(Context);
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite objElevatedSite = new SPSite(objWeb.Site.ID))
{


using (SPWeb objElevatedWeb = objElevatedSite.OpenWeb())
{
// Allow unsafe updates because you can’t save changes
// during HTTP GET requests.
objElevatedWeb.AllowUnsafeUpdates = true;
SPNavigationNode node = new SPNavigationNode( å
“My Custom Node”, “http://node.url”, true);
objElevatedWeb.Navigation.QuickLaunch.AddAsFirst(node);
objElevatedWeb.Update();
}
}
}
);


And this worked fine for me when using Web User Controls. But somehow when i used this structure in web parts, i got the "using disposed SPWeb object no longer supported" error and it was difficult in this context to select an SPWeb which was not the current contextual web.

Thus i submit to thee THIS method which worked perfectly for me.


SPSecurity.CodeToRunElevated objCode = new SPSecurity.CodeToRunElevated(YourMethod);
SPSecurity.RunWithElevatedPrivileges(objCode);


In this scenario, "YourMethod" is a separate method which you call via the delegate.

Make sure to select any specific webs in the following way (or similar)

SPWeb selectedWeb = SPControl.GetContextWeb(Context).Webs[_targetSiteCollection];

(Actually I havent confirmed this but it worked for me and thats where i stopped).

Hope this helps.

No comments: