Set permissions on SharePoint list and items programmatically

This is a short guide on how to set permissions on a SharePoint list/item using server-side object model.

  1. Get the principal object (SPPrincipal) to which you want to grant permission to. It by sharepoint user or group.
  2. Get the list
    SPList list = web.GetListFromUrl(web.Url + “/Lists/ListName/Forms/AllItems.aspx“);
    
  3. Break role inheritance for the list
    list.BreakRoleInheritance(false);
    

    or pass ‘true’ if you want to copy the current role assignments when breaking the role inheritance.

  4. Create new instance of SPRoleAssignment
    SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
    
  5. Create new instance of SPRoleDefinition
    SPRoleDefinition roleDefinition = new SPRoleDefinition();
    
  6. Set the SPRoleType you want to the role definition.
    Example for read permissions:

    	roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
    
  7. Create new instance of SPRoleDefinitionBindingsCollection and add the role definition created above
    SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection();
    
  8. Import the role definition binding collection to the role assignment
    roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection);
    
  9. Add the role assignment to the list’s role assignments collection
        list.RoleAssignments.Add(roleAssignment);
    

Here is the complete code for setting read permissions for a principal:

SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
SPRoleDefinition roleDefinition = new SPRoleDefinition();
roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection();
roleDefinitionBindingCollection.Add(roleDefinition);
roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection);
web.AllowUnsafeUpdates = true;
list.RoleAssignments.Add(roleAssignment);
web.AllowUnsafeUpdates = false;

The same logic is valid for setting item’s permissions by just replacing SPList with SPListItem in the code:

SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
SPRoleDefinition roleDefinition = new SPRoleDefinition();
roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection();
roleDefinitionBindingCollection.Add(roleDefinition);
roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection);
web.AllowUnsafeUpdates = true;
item.RoleAssignments.Add(roleAssignment);
web.AllowUnsafeUpdates = false;

Leave a comment