Running SPSecurity.RunWithElevatedPrivileges in WSS3

When developing a web part or a custom control in WSS/Sharepoint 2007 you might sometimes need to execute some code for which you need more permissions than the one your current user has.
I have this regularly when creating custom controls for Internet Publishing sites in which the anonymous user is the one visiting the site. Say for example that a form is presented to the user that should create new items in a list. An anonymous user does not have a create permission for the list (and we don't want to give the right either).

This can be solved by impersonating the Sharepoint\system user by using the SPSecurity.RunWithElevatedPrivileges method.
MSDN documentation for the method: SPSecurity.RunWithElevatedPrivileges Method (Microsoft.SharePoint).

I ran into a small problem with this method by using it incorrectly… yes my own fault of course but I thought to post an item on this.

Instead of following the example on the MSDN documentation I was using the current context to get an SPWeb object. This does not work because the context has already loaded with the current (anonymous) user’s credentials:

SPSecurity.RunWithElevatedPrivileges(delegate() {
 using (SPSite site = SPControl.GetContextSite(this.Context))
 {

 //implementation here

 }
});

So, always use the web’s ID or URL to load the SPWeb of SPSite object and it works. Just as the documentation shows:

 

SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite site = new SPSite(web.Site.ID))
 {

 // implementation details omitted

 }
});

 

Technorati tags: , ,

 

Feedback

Posted on 25 April 2008 @ 22:21

I tried to use the code of the article.
The row "using (SPSite site = new SPSite(web.Site.ID))" got the following error:
The Web application at http://server_name could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

Thank you.

Posted on 27 April 2008 @ 18:59

Hi Dudan,
Don't forget to correctly load the "web" object which I do not show here. How did you initialize the the object?

Katrien

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Copyright © 2007 Katrien De Graeve.