Wednesday, March 17, 2010

Code to change SPListItem permissions with a non-full-control user

Recently I faced the need to change SharePoint's List Items permissions programmatically. The tricky part of it was the fact that the user performing the action had only contributor rights on the site. The workaround to perform such action is to run the code as a user with elevated privileges. So here is my first approach:
Guid SiteId = SPContext.Current.Site.ID;
Guid
WebId = SPContext
.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using
(SPSite ElevatedSite = new SPSite
(SiteId))
{
using
(SPWeb
ElevatedWeb = ElevatedSite.OpenWeb(WebId))
{
//Code to change permissions

}

}

});

Using this code, at the moment you execute the sentences to change the permissions, you get an error like: "The security validation for this page is invalid". The way to solve this error is to set the AllowUnsafeUpdates property to true for the SPWeb object and validate the form digest control used in the current request. Hence the code snippet will look like this:

Guid SiteId = SPContext.Current.Site.ID;
Guid
WebId = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using
(SPSite ElevatedSite = new SPSite(SiteId))
{
using
(SPWeb ElevatedWeb = ElevatedSite.OpenWeb(WebId))
{
ElevatedWeb.AllowUnsafeUpdates = true;
ElevatedWeb.Update();
SPUtility
.ValidateFormDigest();

//Code to change permissions

ElevatedWeb.AllowUnsafeUpdates = false;
}
}
});

And finally the code to change the permissions would look some thing like this:

listItem.BreakRoleInheritance(false);
SPRoleAssignment
role = new SPRoleAssignment(SPContext.Current.Web.EnsureUser("SOMEUSERorGROUP"));
role.RoleDefinitionBindings.Add(ElevatedWeb.RoleDefinitions.GetByType(SPRoleType.Contributor)); //Or any other SPRoleType
listItem.RoleAssignments.Add(role);
listItem.Update();

This worked for me. Hope it helps!

0 comments:

Post a Comment