Thursday, March 19, 2009

Elevated Permissions with SPContext

Old post I moved over.


I have created a provisioning wizard to control where and how sites are created. I do this through a web part that is added to the STS#1 definition. To prevent users from accessing the site settings menu everyone is setup at the top level as a "Reader". So obviously if i want to create a site, within the users context, i need to elevate their permission. There is plenty of code out there that demostrates the SPSecurity.RunWithElevatedPrivileges, however, if you are to use the SPContext while inside a call to RunWithElevatedPrivileges it does not elevate the current context permission. You will have to open a new site. Examples below:


// Doesn't Work
SPSecurity.RunWithElevatedPrivileges(delegate {
SPWeb web = SPContext.Current.Web {

// provision site & do other jazz
web.Webs.Add(...);
});

// Better
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite site = new SPSite(SPContext.Current.Web.Url)) {
using (SPWeb web = site.OpenWeb()) {
// provision site & do other jazz
web.Webs.Add(...);
}
}
});

Odd but works for me.

No comments:

Post a Comment