I am trying to reset item permissions on ItemAdded and ItemUpdated events, wrote below code to do this job for any user (even for users who don’t have manage permissions on the list item):

SPListItem oItem = properties.ListItem;
Guid siteId = properties.Web.Site.ID;
Guid webId = properties.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteId))
    {
        using (SPWeb oWeb = site.OpenWeb(webId))
        {
            Utility.removeExistingPermissions(oItem);
        }
    }
});

Though removeExistingPermissions() function is calling from elevated block it is still using current user credentials and throwing access denied error. Mistake I was doing is creating list item from properties.ListItem.

We should create list item from elevated web and not from properties, correct code is below:

Guid siteId = properties.Web.Site.ID;
Guid webId = properties.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteId))
    {
        using (SPWeb oWeb = site.OpenWeb(webId))
        {
            SPListItem oItem = oWeb.Lists[properties.ListId].GetItemById(properties.ListItemId);
            Utility.removeExistingPermissions(oItem);
        }
    }
});
Advertisements