SharePoint Security and the Object Model – Part 2

Permissions

This is the second part of a three part post on security object model basics in SharePoint. The other posts are SharePoint Security and the Object Model – Part 1 and SharePoint Security and the Object Model – Part 3.

Defining and Applying Permissions

Authorization in SharePoint is done based on a user’s permission level
for a given context. You can view and manage permission levels by clicking the Permission Levels ribbon button on the People and Groups page.

In the object model the SPRoleDefinition class represents a permission level. The SPRoleDefinition BasePermissions property is a bit mask of SPBasePermission enumeration values. You can bind a role definition to any ISecurableObject via the RoleAssignments property.

The following code shows how to create a permission level that allows editing, but not creation or deletion of items.

SPRoleDefinition def = new SPRoleDefinition();
def.Name = "Edit Not Delete";
def.Description = "Can edit, but can't delete.";


 

def.BasePermissions = SPBasePermissions.ViewListItems |
SPBasePermissions.EditListItems |
SPBasePermissions.Open |
SPBasePermissions.ViewPages;

web.RoleDefinitions.Add(def);

            

Securable Objects and Inheritance

By default, all objects inherit permissions from their parent level. However, as you saw in the previous exercise, you can break inheritance at any level with different permissions for an object and all of its descendants.

Breaking Inheritance

ISecurableObject requires implementation of the BreakRoleInheritance method. SPWeb, SPList, and SPListItem implement ISecurableObject and expose this method.

BreakRoleInheritance accepts a single Boolean argument. BreakRoleInheritance(true) breaks inheritance and copies the role assignments from parent. BreakRoleInheritance(false) breaks role inheritance with no role assignments from parent. A common error is to invoke BreakRoleInheritance(true) when trying to create a unique set of permissions. Because passing true copies the role assignments from the parent, until you modify the role assignments that child object has the same permissions it had before inheritance was broken.

Applying Permissions

Permissions are applied to an ISecurableObject via the RoleAssignments collection. RoleAssignments is a property of type SPRoleAssignmentCollection and contains SPRoleAssignment instances. A role assignment consists of an SPPrincipal (the base class of SPUser and SPGroup) and a collection of RoleDefinitionBindings.

The following code applies a role definition named Create and Edit to a list item and the current SPUser of the web.

void SetPermission(SPListItem item)
{
SPWeb web = item.Web;
item.BreakRoleInheritance(false);

                
SPRoleAssignment assign = new SPRoleAssignment(web.CurrentUser);

assign.RoleDefinitionBindings.Add(
web.RoleDefinitions["Create and Edit"]);

item.RoleAssignments.Add(assign);
}

Author: Doug Ware