Sharepoint RunWithElevatedPrivileges and Access Denied error


Hi everyone,

in this short article i try to explain most common error of Access Denied cause by misusage of SPSecurity.RunWithElevatedPrivileges() method.

Here is the wrong code sample:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    //never use like this
    SPList list = SPContext.Current.Web.Lists["SomeList"];
    SPListItem item = list.GetItemById(12);
    item["Title"] = "Some Changes";
    item.Update();
});

The code defined above cause Access Denied when a user request without privs. Beacuse SPContext still contains unpriviledged user rights.If you call any object from SPContext it work with actual user (unpriviledged) rights not the admin rights.

Now is the correct one:

Guid webID = SPContext.Current.Web.ID;
Guid siteID = SPContext.Current.Site.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteID))
    {
        site.AllowUnsafeUpdates = true;
        using (SPWeb web = site.OpenWeb(webID))
        {
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists["SomeList"]; //attention here !!!
            SPListItem item = list.GetItemById(12);
            item["Title"] = "Some Changes";
            item.Update();
        }
    }
});

Yep its a little extra codding . I give you a good pattern for using this with more easy and shorter usage:
I created once a static class and add to my project this class named RunAsAdmin and one static method named Run which is taking a delegate method for run our  RunWithElevatedPrivileges codes.

public static class RunAsAdmin
{
    public delegate void RunWithAdminDelegate(SPSite site, SPWeb web);
    public static void Run(RunWithAdminDelegate myDelegate)
    {
        Guid webID = SPContext.Current.Web.ID;
        Guid siteID = SPContext.Current.Site.ID;
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(siteID))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb(webID))
                {
                    web.AllowUnsafeUpdates = true;
                    myDelegate.Invoke(site ,web );
                }
            }
        });
    }
}

Usage of this code is:

RunAsAdmin.Run((site,web)=>
 {
    SPList list = web.Lists["SomeList"];
    SPListItem item = list.GetItemById(12);
    item["Title"] = "Some Changes";
    item.Update();
});

Its very useful :))
Happy coding with sharepoint 🙂


Advertisement

About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: