Managing Permission In SharePoint Using Server Object Model

Security is very critical feature that can decide the future and success of any product. With SharePoint, we can manage permissions for users and groups easily, using the Out Of The Box UI.

But sometimes, we might come across a situation where we might need to do the same thing programmatically.

In this blog, I will explain how we can manage SharePoint permission using Server Object Model with the help of C#.

Whenever we are dealing with the SharePoint permissions programmatically, there are two things that might create problems if we do not have any idea - 
 
These two things are classes ,
  1. SPRoleAssignments
  2. SPRoleDefinition
Here, we will not dig into the above classes, but let’s just clear out the purpose of both of the classes. At simplest term, SPRoleAssignments is our container for holding the object (user/group) with appropriate permission or in other words, with the definition (SPRoleDefintion) of the object (user/group). This permission/definition should be referred as SPRoleDefintion.
  1. class Permission  
  2. {  
  3.     public string DisplayName { getset; }  
  4.     public string UserPermissionType { getset; }  
  5.     public string UserPermission { getset; }  
  6.     public string WebURL { getset; }  
  7.     public bool IsUniquePermission { getset; }  
  8.     public string ParentWeb { getset; }  
  9.     public bool IsRootWeb { getset; }  
  10. }  
  11.   
  12. private static List<Permission> permissionObj;  
  13.   
  14. private static void ReadPermission(SPWeb web, string permissionAssignedTo, bool isGroup)  
  15. {  
  16.     try  
  17.     {  
  18.      permissionObj = new List<Permission>();  
  19.         string webTitle = web.Title + web.Url;  
  20.         SPUser user = null;  
  21.   
  22.         if (!isGroup)  
  23.         {  
  24.             user = web.Site.RootWeb.EnsureUser(permissionAssignedTo);  
  25.         }  
  26.         foreach (SPRoleAssignment sourceRoleAsg in web.RoleAssignments)  
  27.         {  
  28.             XElement xmlTree = null;  
  29.             string groupName = string.Empty;  
  30.             string memberName = sourceRoleAsg.Member.LoginName;  
  31.            
  32.          // below condition can be true in two case: if user has direct permission or if any group has permission  
  33.             if (permissionAssignedTo == memberName)  
  34.             {  
  35.                 xmlTree = XElement.Parse(sourceRoleAsg.RoleDefinitionBindings.Xml);  
  36.             }  
  37.             else   
  38.             {  
  39.              // this block will be executed, if user is having permission through any group.  
  40.                 if (user != null && user.Groups.OfType<SPGroup>().Count(u => u.Name.Equals(memberName, StringComparison.InvariantCultureIgnoreCase)) > 0)  
  41.                 {                       
  42.                     groupName = memberName;  
  43.                     xmlTree = XElement.Parse(sourceRoleAsg.RoleDefinitionBindings.Xml);  
  44.                 }  
  45.             }  
  46.   
  47.             if (xmlTree != null)  
  48.             {  
  49.              // read all the permission for user/group and add it to List Object ("permissionObj").  
  50.                 var xmlFilteredData = xmlTree.Elements("Role").Where(xmlNode => xmlNode.Attribute("Name").Value.ToLower() != "limited access")  
  51.                     .Select(xmlNode => new Permission  
  52.                     {  
  53.                         DisplayName = user == null ? permissionAssignedTo : user.Name,  
  54.                         UserPermissionType = groupName == string.Empty ? "Direct Permission" : "<b>Group:</b> " + groupName,  
  55.                         UserPermission = xmlNode.Attribute("Name").Value,  
  56.                         WebURL = web.Url,  
  57.                         IsUniquePermission = web.HasUniqueRoleAssignments,  
  58.                         ParentWeb = web.FirstUniqueAncestorWeb.Url,  
  59.                         IsRootWeb = web.IsRootWeb  
  60.                     });  
  61.   
  62.                 foreach (Permission permission in xmlFilteredData)  
  63.                 {  
  64.                     permissionObj.Add(permission);  
  65.                 }  
  66.             }  
  67.         }  
  68.     }  
  69.     catch (Exception ex)  
  70.     {  
  71.         Common.ErrorLog(ex.Message, "Error reading SPSites - IterateSite()", TraceSeverity.Unexpected);  
  72.     }  
  73. }  
  74.   
  75. public static void RemoveUserPermission(string webURLToRemovePermissionFrom, string directPermissionOrGroup, string userLoginOrGroupName, string permissionToDelete)  
  76. {  
  77.  // value of "permissionToDelete" should be name of permission levels, such as: "Full Control", "Contribute", "Edit", "Read" etc.  
  78.     try  
  79.     {  
  80.         using (SPSite site = new SPSite(webURLToRemovePermissionFrom))  
  81.         {  
  82.             using (SPWeb web = site.OpenWeb())  
  83.             {  
  84.                 web.AllowUnsafeUpdates = true;                          
  85.               
  86.             // below condition will be true if user has direct permission or if we are removing permission of group itself.  
  87.                 if (directPermissionOrGroup == "Direct Permission")  
  88.                 {  
  89.                     SPPrincipal principal = web.RoleAssignments.Cast<SPRoleAssignment>().Where(role => role.Member.LoginName == userLoginOrGroupName).Select(role => role.Member).SingleOrDefault();  
  90.                     SPRoleDefinition roleDefToDelete = web.RoleDefinitions[permissionToDelete];  
  91.                     SPRoleAssignment roleAssignments = web.RoleAssignments.GetAssignmentByPrincipal(principal);  
  92.                     roleAssignments.RoleDefinitionBindings.Remove(roleDefToDelete);  
  93.                     roleAssignments.Update();  
  94.                 }  
  95.                 else // this block will be executed if we want to remove user from specific group to reduce his/her access  
  96.                 {  
  97.                     web.Groups[directPermissionOrGroup.Substring(14)].RemoveUser(web.EnsureUser(userLoginOrGroupName));  
  98.                 }  
  99.   
  100.                 web.AllowUnsafeUpdates = false;  
  101.                 web.Update();  
  102.             }  
  103.         }  
  104.     }  
  105.     catch (Exception ex)  
  106.     {  
  107.         Common.ErrorLog(ex.Message, "Error deleting SharePoint Permission - RemoveUserPermission()", TraceSeverity.Unexpected);  
  108.     }  
  109. }  
  110.   
  111. public static void AssignPermissioToUser(string webToAssignPermission, string permissionAssignee, string permissionToApply)  
  112. {  
  113.  // value of "permissionToApply" should be name of permission levels, such as: "Full Control", "Contribute", "Edit", "Read" etc. OR Name of the group in which we want to add user.  
  114.     try  
  115.     {  
  116.         using (SPSite site = new SPSite(webToAssignPermission))  
  117.         {  
  118.             using (SPWeb web = site.OpenWeb())  
  119.             {  
  120.                 web.AllowUnsafeUpdates = true;  
  121.                 try  
  122.                 {  
  123.                     SPPrincipal principal = web.EnsureUser(permissionAssignee); // if variable "permissionAssignee" contains group name then code in Catch block will be executed.  
  124.                       
  125.                  // if "permissionToApply" contains group name to which we want to add user, then, ELSE block will be executed  
  126.                  var spRoleDefinition = web.RoleDefinitions.OfType<SPRoleDefinition>().Where(definition => definition.Name == permissionToApply).SingleOrDefault();  
  127.                     if (spRoleDefinition != null)  
  128.                     {  
  129.                         SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);  
  130.                         roleAssignment.RoleDefinitionBindings.Add(spRoleDefinition);  
  131.                         web.RoleAssignments.Add(roleAssignment);  
  132.                     }  
  133.                     else  
  134.                     {  
  135.                         web.Groups[permissionToApply].AddUser(SPContext.Current.Site.RootWeb.EnsureUser(permissionAssignee));  
  136.                     }  
  137.                 }  
  138.                 catch  
  139.                 {  
  140.                  // if variable "permissionAssignee" contains group name then code then this code will be executed.  
  141.                  // This means, we want to assign permission tto group itself.  
  142.                     SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[permissionAssignee]);  
  143.                     SPRoleDefinition roleDefinition = web.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(definition => definition.Name == permissionToApply);  
  144.                     roleAssignment.RoleDefinitionBindings.Add(roleDefinition);  
  145.                     web.RoleAssignments.Add(roleAssignment);  
  146.                 }  
  147.   
  148.                 web.AllowUnsafeUpdates = false;  
  149.                 web.Update();  
  150.             }  
  151.         }  
  152.     }  
  153.     catch (Exception ex)  
  154.     {  
  155.         Common.ErrorLog(ex.Message, "Error assigning SharePoint Permission - AssignPermissioToUser()", TraceSeverity.Unexpected);  
  156.     }