Configure Your Code to Run With Elevated Privileges

If you’re doing any sort of custom development within the MOSS framework, there might come a time when you’ll need to execute your code with elevated permissions. Meaning, instead of your code running under the context of the current user, you’ll want to run it using an account with a higher level of access.

Within MOSS, there is a method that will do the trick. The RunWithElevatedPrivileges method will run under the context of the Application Pool Identity account.

As an example: The code below was taken from an application page I developed recently. When running this code using my credentials, it executed without trouble. Once logged in as a user with Contribute access, I was running into an Access Denied SharePoint error.

1
2
3
4
5
void DoSubmit(object sender, EventArgs e)
{
    SPSite site = SPControl.GetContextSite(Context);
    SPWebCollection webs = site.AllWebs;
}

My next step was to attempt to run the DoSubmit method using elevated privileges as follows.

1
2
3
4
5
6
7
8
9
10
void DoSubmit(object sender, EventArgs e)
{
    SPSecurity.RunWithElevatedPrivileges(GetExpiredPages);
}
 
void GetExpiredPages()
{
    SPSite site = SPControl.GetContextSite(Context);
    SPWebCollection webs = site.AllWebs;
}

The above code was still producing an Access Denied error. It took me a moment to realize what I was doing wrong. The trick was that I needed to create a NEW SPSite object INSIDE the function that I am trying to run using elevated privileges. If I don’t recreate the SPSite object, I’ll essentially still be executing my code under the context of the current user.

1
2
3
4
5
void GetExpiredPages()
{
    SPSite site = new SPSite(SPControl.GetContextSite(Context).ID);
    SPWebCollection webs = site.AllWebs;
}

,

3 Responses to “Configure Your Code to Run With Elevated Privileges”

  1. Rick Boruff September 30, 2011 at 12:05 am #

    Excellent work! Thanks for sharing the information

  2. Richard November 3, 2014 at 4:06 pm #

    Thanks for sharing, helped me understanding why an exception was being thrown.

Trackbacks/Pingbacks

  1. Tech News - March 29, 2011

    […] This post was mentioned on TechWench […]…

    […] Read the rest of this excellent post here…. […]…

Leave a Reply