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 ,
- SPRoleAssignments
- 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.
- class Permission
- {
- public string DisplayName { get; set; }
- public string UserPermissionType { get; set; }
- public string UserPermission { get; set; }
- public string WebURL { get; set; }
- public bool IsUniquePermission { get; set; }
- public string ParentWeb { get; set; }
- public bool IsRootWeb { get; set; }
- }
-
- private static List<Permission> permissionObj;
-
- private static void ReadPermission(SPWeb web, string permissionAssignedTo, bool isGroup)
- {
- try
- {
- permissionObj = new List<Permission>();
- string webTitle = web.Title + web.Url;
- SPUser user = null;
-
- if (!isGroup)
- {
- user = web.Site.RootWeb.EnsureUser(permissionAssignedTo);
- }
- foreach (SPRoleAssignment sourceRoleAsg in web.RoleAssignments)
- {
- XElement xmlTree = null;
- string groupName = string.Empty;
- string memberName = sourceRoleAsg.Member.LoginName;
-
-
- if (permissionAssignedTo == memberName)
- {
- xmlTree = XElement.Parse(sourceRoleAsg.RoleDefinitionBindings.Xml);
- }
- else
- {
-
- if (user != null && user.Groups.OfType<SPGroup>().Count(u => u.Name.Equals(memberName, StringComparison.InvariantCultureIgnoreCase)) > 0)
- {
- groupName = memberName;
- xmlTree = XElement.Parse(sourceRoleAsg.RoleDefinitionBindings.Xml);
- }
- }
-
- if (xmlTree != null)
- {
-
- var xmlFilteredData = xmlTree.Elements("Role").Where(xmlNode => xmlNode.Attribute("Name").Value.ToLower() != "limited access")
- .Select(xmlNode => new Permission
- {
- DisplayName = user == null ? permissionAssignedTo : user.Name,
- UserPermissionType = groupName == string.Empty ? "Direct Permission" : "<b>Group:</b> " + groupName,
- UserPermission = xmlNode.Attribute("Name").Value,
- WebURL = web.Url,
- IsUniquePermission = web.HasUniqueRoleAssignments,
- ParentWeb = web.FirstUniqueAncestorWeb.Url,
- IsRootWeb = web.IsRootWeb
- });
-
- foreach (Permission permission in xmlFilteredData)
- {
- permissionObj.Add(permission);
- }
- }
- }
- }
- catch (Exception ex)
- {
- Common.ErrorLog(ex.Message, "Error reading SPSites - IterateSite()", TraceSeverity.Unexpected);
- }
- }
-
- public static void RemoveUserPermission(string webURLToRemovePermissionFrom, string directPermissionOrGroup, string userLoginOrGroupName, string permissionToDelete)
- {
-
- try
- {
- using (SPSite site = new SPSite(webURLToRemovePermissionFrom))
- {
- using (SPWeb web = site.OpenWeb())
- {
- web.AllowUnsafeUpdates = true;
-
-
- if (directPermissionOrGroup == "Direct Permission")
- {
- SPPrincipal principal = web.RoleAssignments.Cast<SPRoleAssignment>().Where(role => role.Member.LoginName == userLoginOrGroupName).Select(role => role.Member).SingleOrDefault();
- SPRoleDefinition roleDefToDelete = web.RoleDefinitions[permissionToDelete];
- SPRoleAssignment roleAssignments = web.RoleAssignments.GetAssignmentByPrincipal(principal);
- roleAssignments.RoleDefinitionBindings.Remove(roleDefToDelete);
- roleAssignments.Update();
- }
- else
- {
- web.Groups[directPermissionOrGroup.Substring(14)].RemoveUser(web.EnsureUser(userLoginOrGroupName));
- }
-
- web.AllowUnsafeUpdates = false;
- web.Update();
- }
- }
- }
- catch (Exception ex)
- {
- Common.ErrorLog(ex.Message, "Error deleting SharePoint Permission - RemoveUserPermission()", TraceSeverity.Unexpected);
- }
- }
-
- public static void AssignPermissioToUser(string webToAssignPermission, string permissionAssignee, string permissionToApply)
- {
-
- try
- {
- using (SPSite site = new SPSite(webToAssignPermission))
- {
- using (SPWeb web = site.OpenWeb())
- {
- web.AllowUnsafeUpdates = true;
- try
- {
- SPPrincipal principal = web.EnsureUser(permissionAssignee);
-
-
- var spRoleDefinition = web.RoleDefinitions.OfType<SPRoleDefinition>().Where(definition => definition.Name == permissionToApply).SingleOrDefault();
- if (spRoleDefinition != null)
- {
- SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
- roleAssignment.RoleDefinitionBindings.Add(spRoleDefinition);
- web.RoleAssignments.Add(roleAssignment);
- }
- else
- {
- web.Groups[permissionToApply].AddUser(SPContext.Current.Site.RootWeb.EnsureUser(permissionAssignee));
- }
- }
- catch
- {
-
-
- SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[permissionAssignee]);
- SPRoleDefinition roleDefinition = web.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(definition => definition.Name == permissionToApply);
- roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
- web.RoleAssignments.Add(roleAssignment);
- }
-
- web.AllowUnsafeUpdates = false;
- web.Update();
- }
- }
- }
- catch (Exception ex)
- {
- Common.ErrorLog(ex.Message, "Error assigning SharePoint Permission - AssignPermissioToUser()", TraceSeverity.Unexpected);
- }
- }