Tuesday, August 31, 2010

SharePoint Item Level Permission

I am working on a requirement to secure a SharePoint list item and when I was reading about it on MSDN for the first time, I got very confused because of the class names associated with SharePoint security. SO I thought let me post a very basic article explaining how to change item level permission.

From the SharePoint UI this can be done by breaking the permission inheritance at item level and then by changing everybody's permission to read only. Go to Item Level Permission>Actions>Edit Permissions>Break Inheritance>Select all the user groups/users and give them the required permissions, in my case I am giving them read access, so that no one can change the list item once it has been submitted.

So how to change list level permission programmatically? Well, we need to make use of object model and this is one way of doing it.

The basics for getting permissions programmatically right are RoleAssignment and RoleDefinition. Users, User Groups are synonymous to RoleAssignments in the object model and permissions (Read, contribute, Owner etc) are synonymous to RoleDefinition.

So let's get started

1.) Break Inheritance
The parameter false indicates that after breaking inheritance don’t copy any of the users from the list level, if you select true then users will get copied over to the item level.

2.) I selected false in first step because I don’t want to copy the users directly from the list level.
I will loop through all the users and user groups at the list level and add them with only read access to item. Here is the code for that, I was using this from inside a workflow, that why you see workflowProperties, workflowProperties.Item is just a SPListItem object.

//create a roledefinition for read access
SPRoleDefinition oRoleDefinition_Read = workflowProperties.Web.RoleDefinitions["Read"];
//loop through the user and groups at list level
foreach (SPRoleAssignment oRoleAssignment in workflowProperties.List.RoleAssignments)
//Remove all definitions(permissions)associated with the Role Assigments(Users and group)
//Add the read only definition to role assignment
//bind the the new role assignment to the item.
3.) Then update the item and you are done.

We are using SharePoint WSS 3.0, MS SQL 2008, and Visual Studio 2005.

No comments:

Post a Comment