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
}
});