Archive for May, 2011

RunWithElevatedPrivileges throws Access Denied Exception

May 8, 2011

There are more reasons why you can receive this exception. The obvious one is that you use SPContext in the elevated block. For more info see this post . I will  describe a less obvious reason in following article. The RunWithElevatedPrivileges method runs the code under the account of the application pool. In the productive environments has the application pool account only limited privileges. Generally the permissions are so defined that you can do anything you want in the current site however if you try to run e.g following code:

var webApp = SPWebApplication.Lookup(new Uri("http://localhost/sites"));
webApp.Sites.Add("http://localhost/sites/", "user", "email");

you will receive the access denied exception. So how to solve this problem:

  1. Define an account that has only the needed permissions to perform the desired operation. In this specific scenario, you can define a user that has self service site creation permissions and modify the code that it uses self service site creation.
  2. Run the code, that throws exception under the specified account. You can achieve this for example so, that you open the SPSite impersonated. See this.