Pages

Wednesday, March 23, 2011

Working with custom permission levels in SharePoint

Creating custom permission levels in SharePoint is not hard. You can do it through the GUI, by navigating to the_layouts/addrole.aspx page on any site.
But you might want to do it through code instead, deploying the new permission level with a feature and assigning it to groups and users. This also includes more options for defining the permission level than the GUI does. Below I show how to define your own permission levels.

Should you want to see what permissions are used for the standard permission levels, then this link is a good place to look.


Imagine that we need a permission level that lets the user do all the things they normally do through the 'Contribute' permission level, EXCEPT deleting list items.

We could solve this by using the ItemDeleting event receiver, but that is not a user-friendly way - first giving them the option to delete an item (through the ECB menu), then telling them that they can't do it anyway. Instead, we create and deploy a custom permission level, after which SharePoint will ensure that users are only presented with the actions they are allowed to perform.

Create a custom permission level

First we create a feature, and add a feature receiver.
<?xml version="1.0" encoding="utf-8"?>
<Feature
  Id="{MyGuid}"
  Title="My feature"
  Scope="Web"
  ReceiverAssembly="My four-part assembly name"
  ReceiverClass="MyNamespace.MyFeatureReceiver"
  xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
  </ElementManifests>
</Feature>

Then, in the feature receiver, we define the new permission level. By the way, code-wise it is called a SPRoleDefinition. We need to define which permissions the permission level should include. In our example we will base it on the permissions for the Contribute permission level, but remove the permissions to delete.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
  var web = (SPWeb)properties.Feature.Parent;
  var contribRoleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
  var newRoleDef = new SPRoleDefinition();
  newRoleDef.Name = "My permission level";
  newRoleDef.Description = "Description of my permission level.";
  newRoleDef.BasePermissions = contribRoleDef
    ^ SPBasePermissions.DeleteListItems
    ^ SPBasePermissions.DeleteVersions;
  web.RoleDefinitions.Add(newRoleDef);
}

Note that it is not necessary to call web.Update().

Assign the custom permission level to a member

To assign the custom permission level to a member (user or group), do the following (in a feature receiver, or whereever you want to run the code):

var assignment = new SPRoleAssignment(myMember);
assignment.RoleDefinitionBindings.Add(web.RoleDefinitions["My permission level"]);
web.RoleAssignments.Add(assignment);
web.Update();

Have a nice permission.

No comments:

Post a Comment