Tuesday 1 July 2014

Access denied using SPSecurity.RunWithElevatedPrivileges - Sharepoint 2010

SPSecurity.RunWithElevatedPrivileges - Sharepoint 2010

--Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.

Whenever we use SPSecurity.RunWithElevatedPrivileges(), it will execute the code under the context of Application Pool identity. Now we can see a scenario where we will get the “Access denied” exception from the code block even if you use SPSecurity.RunWithElevatedPrivileges.

Using SharePoint context with an unauthenticated user does not actually elevate privileges:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // do something with SPContext.Current.Web 
    // fails with a AccessDenied Exception
    // because SPContext is loaded with the site,
    // not within this delegate block.
   // if anonymous user logged in, context will be loaded with the ANONYMOUS USER's only.
});

So to get actual elevated privileges (i.e., App Pool Identity), you have to reload the context:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(SPContext.Current.Web.Site.Url))
    {
        using (SPWeb oWeb = site.OpenWeb())
        {
            // do something with oWeb
                    // oWeb is loaded with the Application pool identity
        }
    }
});


Happy Coding J..


No comments:

Post a Comment