Thursday, October 21, 2010

Unique Permissions in SharePoint 2010 List

Have you ever wondered how to manage the permissions of a list in C# on a SharePoint list? here's you solution. It's pretty simple really. Just do the following.

FYI, if you want to do this on a list item, just iterate through each item of you list until you find the one you want and you'll find the HasUniquePermissions, BreakRoleInheritance, and RoleAssignments there too. Just treat them the same way you treat the list below.



//Here we get our context
SPContext context = SPContext.Current;

//We define a new role assignment using a login name. You could do this by email if you like, or using any of the other fields avaliable.
SPRoleAssignment ra = new SPRoleAssignment("DOMAIN\\userName", "", "", "");
//Here we assign the permission we are going to give the RA. In this case, I'm using read, but it can be any of the permission levels you have stored in SharePoint.
ra.RoleDefinitionBindings.Add(context.Web.RoleDefinitions["Read"]);

//We get our list instance.
SPList list = context.Web.Lists["List Name"];

//We check if this list has unique permissions.
if (!list.HasUniqueRoleAssignments)
{
//If it doesn't, we make it have unique permissions here. Pass true to copy from parent, false to start with clean permissions.
list.BreakRoleInheritance(false);
}

//We now add our RA
list.RoleAssignments.Add(ra);

//Update the list to save it to SharePoint
list.Update();

2 comments:

  1. You can also get the SPUser first by doing:
    SPUser user = context.Web.EnsureUser("DOMAIN\\userName");
    SPRoleAssignment ra = new SPRoleAssignment(user);

    Also be sure you run these commands with elevated priveleges or as system account. It has to be the current user (context) with ManagePermissions right.

    ReplyDelete
  2. Good note! I never had a problem with my code that required elevated privileges because the only people who were accessing the web part executed this code were admins.

    ReplyDelete