Working with SharePoint permissions is not always straight forward. This code snippet is an exercise using PnP Core to modify permissions on lists with unique (broken) permissions. All assigned permissions are changed to read only, except for owners group of the site. The code is hopefully a good starting point for similar tasks, and should be easy to adapt to list items if needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
var siteGroups = new Dictionary<int, string>(); await context.Web.SiteGroups.LoadAsync(p => p.Title, p => p.Id); await foreach (var group in context.Web.SiteGroups) { siteGroups.Add(group.Id, group.Title); } await context.Web.LoadAsync(p => p.Title, p => p.AssociatedMemberGroup, p => p.AssociatedOwnerGroup, p => p.AssociatedVisitorGroup, p => p.RoleDefinitions, p => p.Lists.QueryProperties(p => p.Id, p => p.TemplateType, p => p.Title, p => p.HasUniqueRoleAssignments, p => p.RoleAssignments, p => p.DocumentTemplate)); int ReadRoleDefinitionId = 1073741826; var readerRoleDefinition = context.Web.RoleDefinitions.FirstOrDefault(p => p.Id == ReadRoleDefinitionId); if(readerRoleDefinition == null) { throw new Exception("Reader role not found"); } foreach (var list in context.Web.Lists.AsRequested().Where(p => p.TemplateType == PnP.Core.Model.SharePoint.ListTemplateType.DocumentLibrary)) { Console.WriteLine("Processing List: " + list.Title); if (list.HasUniqueRoleAssignments == true) { var roleAssignments = (await list.GetAsync(p => p.All, p => p.RoleAssignments.QueryProperties(p => p.All))).RoleAssignments; foreach (var roleAssignment in roleAssignments) { if(siteGroups.ContainsKey(roleAssignment.PrincipalId)) { Console.WriteLine($" Group: {siteGroups[roleAssignment.PrincipalId]} ({roleAssignment.PrincipalId})"); } else { var user = await context.Web.GetUserByIdAsync(roleAssignment.PrincipalId); Console.WriteLine($" User: {user.Title} ({roleAssignment.PrincipalId})"); } if (roleAssignment.PrincipalId != context.Web.AssociatedOwnerGroup.Id) { var changeRole = false; var roleDefs = await list.GetRoleDefinitionsAsync(roleAssignment.PrincipalId); foreach (var def in roleDefs.AsRequested()) { Console.WriteLine(" : Current role definition: " + def.Name + " (" + def.Id + ")"); if(def.Id != ReadRoleDefinitionId) { changeRole = true; Console.WriteLine(" : Remove role..."); await list.RemoveRoleDefinitionAsync(roleAssignment.PrincipalId, def); } } if (changeRole) { Console.WriteLine(" : Assign as reader..."); await list.AddRoleDefinitionAsync(roleAssignment.PrincipalId, readerRoleDefinition); } } } } } |