Search This Blog

Thursday, September 18, 2014

SharePoint Permission Levels And Role Definitions In C#

A very common requirement for SharePoint developers is to assign out of the box and/or custom SharePoint permission levels to sites (SPWeb objects) or lists and document libraries (SPList objects) or even list items (SPListItem objects).
Windows SharePoint Services manages permissions through role definitions. TheSPRoleDefinition class and theSPRoleAssignment class provides methods to assign users to roles. These classes will be used repeatedly in the examples provided here.
Note: The GetByType() method used in the code examples below returns an object ofSPRoleDefinition type.
 

SharePoint Permission Levels

When you create a new SharePoint site, a number of permission levels are automatically added out of the box. They include:
  • Full Control: This permission level contains all permissions. By default, the Site Owners group has Full Control. This permission level cannot be customized or deleted.
  • Design: Can create lists and document libraries, edit pages and apply themes, borders, and style sheets in the Web site. Not assigned to any group by default. So an administrator must assign this permission level explicitly.
  • Contribute: Can add, edit, and delete items in existing lists and document libraries. By default, the Site Members group has Contribute permissions.
  • Read: Read-only access to the Web site. Users and groups that have this permission level can view items and pages, open items, and documents. By default, the Site Visitors group has Read permission.
  • Limited Access: By design, the Limited Access permission should be combined with fine-grained permissions. You can use this permission to give users access to a specific list, document library, item, or document, without giving them access to the whole site. However, to access a list or library, for example, a user must have permission to open the parent Web site and read shared data such as the theme and navigation bars of the Web site. The Limited Access permission level cannot be customized or deleted.
    Note: You cannot assign this permission level to users or security groups. Instead, the system automatically assigns this permission level to users and security groups when you grant them access to an object on your site that requires that they have access to a higher level object on which they do not have permissions. For example, if you grant users access to an item in a list and they do not have access to the list itself, the system automatically grants them Limited Access on the list. If the user also requires access to the site, the system automatically grants Limited Access to the site.
  • Manage Hierarchy: Can create sites and edit pages, list items, and documents. By default, the Hierarchy Managers group has Manage Hierarchy permissions.
  • Approve: Can edit and approve pages, list items, and documents. By default, the Approvers group has this permission.
  • Restricted Read: Can view pages and documents, but cannot view historical versions or user permissions.

    Access SharePoint Permission Levels In C#

    The above OOTB SharePoint permission levels can be accessed programmatically with C# using the SPRoleType enumeration. Here’s how the SPRoleType enumeration members map to the permission levels:

    Permission Level        SPRoleType Member
    Full ControlSPRoleType.Administrator
    DesignSPRoleType.WebDesigner
    ContributeSPRoleType.Contributor
    ReadSPRoleType.Reader
    Limited AccessSPRoleType.Guest
    ApproveSPRoleType.None
    Manage HierarchySPRoleType.None
    Restricted ReadSPRoleType.None
    Notice that the Approve, Manage Hierarchy and Restricted Read permission levels all map toSPRoleType.None. We will discuss the significance of this later and show how to work with these particular SharePoint permission levels programmatically.
     

    Site Permissions (SPWeb)

    Here’s how to assign the Read permission to a hypothetical SharePoint group (called “All Staff”) on an entire site level. Our site object (SPWeb) is called xWeb.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if (!xWeb.HasUniqueRoleAssignments)
    {
        xWeb.BreakRoleInheritance(false, false);
    }
    xWeb.AllowUnsafeUpdates = true;
    xWeb.Update();
     
    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)xWeb.SiteGroups["All Staff"]);
    roleAssignment.RoleDefinitionBindings.Add(xWeb.RoleDefinitions.GetByType(SPRoleType.Reader));
    xWeb.RoleAssignments.Add(roleAssignment);
    xWeb.AllowUnsafeUpdates = false;
    xWeb.Update();

    List And Document Library Permissions (SPList)

    Here’s how to assign the Read permission to a hypothetical SharePoint group (called “All Staff”) for a specific document library (called “Special Documents”). Our site object (SPWeb) is called xWeb and our document library object (SPList) is called “page”.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    SPList page = xWeb.Lists.TryGetList("Special Documents");
    if (!page.HasUniqueRoleAssignments)
    {
        page.BreakRoleInheritance(false, false);
    }
    page.Update();
    xWeb.Update();
     
    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)xWeb.SiteGroups["All Staff"]);
    roleAssignment.RoleDefinitionBindings.Add(xWeb.RoleDefinitions.GetByType(SPRoleType.Reader));
    page.RoleAssignments.Add(roleAssignment);
    page.Update();
    xWeb.Update();
    The exact same method would apply if we were working with a list instead of a document library because lists and libraries are both SPList objects.

    List Item Permissions (SPListItem)

    Use the same method as above. But this time, you just work with an SPListItem object instead.
     

    “Approve”, “Manage Hierarchy” And “Restricted Read” Permissions

    Now it gets interesting 
    As earlier mentioned, the Approve, Manage Hierarchy and Restricted Read permission levels all map to SPRoleType.None. This means that we can’t retrieve these role definitions using theSPRoleDefinitionCollection.GetByType() method.
    Restricted Read is special role – it is shown for example when a user has access on some folder in the list, but does not have access to the whole list or web site. In most cases we do not use this role programmatically.
    But what about the Manage Hierarchy and Approve roles? We also can’t use the SPRoleDefinitionCollection.GetByType() method to get them programmatically. I explain two methods we can use below.

    Method 1: Hardcode it!

    The quickest way to deal with this is probably to just hardcode the name of the permission level and then do an explicit type cast. Like this:
    1
    2
    string roleName = "Manage Hierarchy";
    SPRoleDefinition roleDefinition = xWeb.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(r => r.Name == roleName);
    You can then use the SPRoleDefinition object like this:
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    The problem with this method is that if you have multilingual topology, the “Manage Hierarchy” permission level will be localized according to the language of the website. In this case, the best approach would be to use method 2 below.

    Method 2: Grab it with this Custom Class

    Create this custom class:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Resources;
    using System.Reflection;
    using System.Globalization;
     
    namespace ExampleCode
    {
        public class PublishingResources
        {
            private static ResourceManager resourceManager;
            static PublishingResources()
            {
                var resourceAssembly = Assembly.Load("Microsoft.SharePoint.Publishing.intl, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
                resourceManager = new ResourceManager("Microsoft.SharePoint.Publishing.Strings", resourceAssembly);
            }
            internal static string GetString(string resourceName, CultureInfo cultureInfo)
            {
               return resourceManager.GetString(resourceName, cultureInfo);
            }
        }
    }
    You can now retrieve the “Manage Hierarchy” permission level programmatically without needing to hardcode anything. Here’s how:
    1
    2
    3
    4
    5
    6
    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)parentWeb.SiteGroups["All Staff"]);
    string roleName = PublishingResources.GetString(StringIds.RoleNameHierarchyManager, xWeb.UICulture);
    SPRoleDefinition roleDefinition = xWeb.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(r => r.Name == roleName);
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    xWeb.RoleAssignments.Add(roleAssignment);
    xWeb.Update();
    If you want to work with the “Approve” permission level instead, just replace StringIds.RoleNameHierarchyManager with StringIds.RoleNameApprover.
    I have tested this code with SharePoint 2010. For SharePoint 2013, we might need to make a few changes in the Assembly.Load() method.

    Custom SharePoint Permission Levels

    If we manually extend an OOTB SharePoint permission level to create a custom permission level, we can assign the custom permission level in C# by referencing the custom permission level by its exact name.
    For example, let’s say we extended the “Contribute” permission level to create a “Restricted Contribute” level. Here’s how the code would look like if we wanted to assign our new permission level to a SharePoint group called “All Staff” for an entire site:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if (!xWeb.HasUniqueRoleAssignments)
    {
        xWeb.BreakRoleInheritance(false, false);
    }
    xWeb.AllowUnsafeUpdates = true;
    xWeb.Update();
     
    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)xWeb.SiteGroups["All Staff"]);
    roleAssignment.RoleDefinitionBindings.Add(xWeb.RoleDefinitions["Restricted Contribute"]);
    xWeb.RoleAssignments.Add(roleAssignment);
    xWeb.AllowUnsafeUpdates = false;
    xWeb.Update();

    Role Assignment for Active Directory (AD) Groups

    It’s easy.
    Let’s say we wanted to do the same thing we did in our first example Site Permissions (SPWeb). But this time, instead of a SharePoint group, we want to use an AD group like this: ourdomain\all staff
    All we need to do is to replace this line:
    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)xWeb.SiteGroups["All Staff"]);
    with this one:
    SPRoleAssignment roleAssignment = new SPRoleAssignment(xWeb.AllUsers[@"ourdomain\all staff"]);


No comments:

Post a Comment