Andrew Kennel

Web Developer

Removing permissions from a Sharepoint list item

June 29, 2009

I recently came across an interesting problem while working on an Infopath form. As part of the submission process, I needed to remove all the permissions from my new document. This seemed easy to do using by calling Item.BreakRoleInheritence = true and then removing all the existing permissions from the item. When I published my form,…

I recently came across an interesting problem while working on an Infopath form. As part of the submission process, I needed to remove all the permissions from my new document. This seemed easy to do using by calling Item.BreakRoleInheritence = true and then removing all the existing permissions from the item.

When I published my form, I found that my approach generated an error: An exception of type ‘System.UnauthorizedAccessException’ occurred in Microsoft.SharePoint.dll but was not handled in user code. Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

This error occured for any user who had Contribute access to the form library. 
 

After a bit of searching, I found this article: http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/c3d2b304-7fcc-40d2-86ce-61d9b21b03d7 Look for the reply made by Kjetil Gullen on July 27.

The answer lies with how the .BreakRoleInheritence interacts with web.AllowUnsafeUpdates = true.  I won’t go into the full explanation as the poster does an excellent job, but below is a code snippet that shows how to do this correctly.
 

SPSecurity.RunWithElevatedPrivileges(delegate()

{

SPWeb _webInUserContext = SPContext.Current.Web;

SPSite _siteInUserContext = SPContext.Current.Site;

Guid _webGuid = _webInUserContext.ID;

Guid _siteGuid = _siteInUserContext.ID;

using (SPSite site = new SPSite(siteGuid))

{

_site.AllowUnsafeUpdates = true;//Allow Unsafe Updates for the Site

SPWeb web = _site.OpenWeb(webGuid);

_web.AllowUnsafeUpdates = true;//Allow Unsafe Updates for the Web

SPList docList = _web.Lists[“Requests”];

SPListItem itemListItem = docList.Items.GetItemById(itemListID);

itemListItem.Web.AllowUnsafeUpdates = true;//Web as referenced by the item

itemListItem.BreakRoleInheritance(true);//Break your inheritence

itemListItem.Web.AllowUnsafeUpdates = true;//Breaking inheritence resets

//Unsafe Updates, reenable it

//Remove the permissions one by one

foreach (SPRoleAssignment spra in itemListItem.RoleAssignments)

{

spra.RoleDefinitionBindings.RemoveAll();

spra.Update();

}

});}

Share This Post