SharePoint Online - Grant And Remove Unique Permissions To Doc Library Using CSOM

For one of our provider-hosted apps, we had a situation where we had to Grant and Remove permissions to folders in a Document Library of a SharePoint Online site.

This blog gives the code for achieving it. In the code, you will see how:

  • It fetches the User ID and Password from the config file to log into the SharePoint site.
  • It uses SecureString to secure the Password. You have to use “using System.Security” to achieve this.
  • It also checks if the folder has unique permission before attempting to grant or remove permission. If not, it breaks the inheritance before granting or removing the permission.
  • Both, GrantPermission and RemovePermission, methods take string array with user accounts. In my case, we have only the user id in the array, so you will see we add “@domain.com” to get the email Id.

So, here is the code to grant permission.

  1. private static void GrantPermissionTo(params string[] accounts)  
  2.         {  
  3.             var DocumentLibName= "<YourDocumentLibraryName>"  
  4.             context = new ClientContext(webUrl);  
  5.             context.Credentials = new SharePointOnlineCredentials(userId, FetchPasswordFromConsole());  
  6.             Web web = context.Web;  
  7.             context.Load(web);  
  8.             context.ExecuteQuery();                 
  9.              
  10.             context.Load(web.Lists);  
  11.             context.ExecuteQuery();  
  12.             context.Load(web.SiteUsers);  
  13.             context.ExecuteQuery();  
  14.             context.Load(web.RoleDefinitions);  
  15.             context.ExecuteQuery();  
  16.             context.Load(web.RoleAssignments);  
  17.             context.ExecuteQuery();  
  18.               
  19.             var list = web.Lists.OfType<List>().FirstOrDefault(l => l.Title.Equals(DocumentLibName, StringComparison.CurrentCultureIgnoreCase));  
  20.             context.Load(list);              
  21.             context.Load(list.RootFolder);  
  22.             context.ExecuteQuery();  
  23.             context.Load(list.RootFolder.Folders);  
  24.             context.ExecuteQuery();  
  25.             
  26.             var folderName = Path.GetFileName("<YourFolderName>");  
  27.             var folder = list.RootFolder.Folders.OfType<Folder>().FirstOrDefault(t => t.Name == folderName);  
  28.             if (folder == null)  
  29.                 return;  
  30.             context.Load(folder);  
  31.             context.ExecuteQuery();  
  32.             context.Load(  
  33.                 folder,  
  34.                 fields => fields.ListItemAllFields,  
  35.                 fields => fields.ListItemAllFields.HasUniqueRoleAssignments,  
  36.                 fields => fields.ListItemAllFields.RoleAssignments);  
  37.             context.ExecuteQuery();  
  38.              
  39.             if (!folder.ListItemAllFields.HasUniqueRoleAssignments)  
  40.             {  
  41.                 folder.ListItemAllFields.BreakRoleInheritance(truetrue);  
  42.                 context.ExecuteQuery();  
  43.             }  
  44.              
  45.             Array.ForEach(accounts, account =>  
  46.             {  
  47.                 account =  account+"@"+<YourDomain>+".com";  
  48.                 try  
  49.                 {  
  50.                     RoleDefinition def;  
  51.                     //ForReadOnly  
  52.                         def = web.RoleDefinitions.GetByName("Read");  
  53.                     //ForContribute  
  54.                         def = web.RoleDefinitions.GetByName("Contribute");  
  55.                     RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(context);  
  56.                     rdb.Add(def);  
  57.                     Principal usr = context.Web.EnsureUser(account);                     
  58.                     folder.ListItemAllFields.RoleAssignments.Add(usr, rdb);  
  59.                 }  
  60.                 catch (Exception ex)  
  61.                 {  
  62.                     WriteLogMessage(ex.Message);  
  63.                 }  
  64.             });  
  65.             folder.Update();  
  66.             context.ExecuteQuery();  
  67.         }  
 And this is the code to remove permission.
  1. private static void RemovePersmissionFrom(params string[] accounts)  
  2.         {  
  3.             var DocumentLibName= "<YourDocumentLibraryName>"  
  4.             context = new ClientContext(webUrl);  
  5.             context.Credentials = new SharePointOnlineCredentials(userId, FetchPasswordFromConsole());  
  6.             Web web = context.Web;  
  7.             context.Load(web);  
  8.             context.ExecuteQuery();    
  9.   
  10.             var web = WebSite;  
  11.             context.Load(web.Lists);  
  12.             context.ExecuteQuery();  
  13.             context.Load(web.SiteUsers);  
  14.             context.ExecuteQuery();  
  15.             context.Load(web.RoleDefinitions);  
  16.             context.ExecuteQuery();  
  17.             context.Load(web.RoleAssignments);  
  18.             context.ExecuteQuery();  
  19.   
  20.             var list = web.Lists.OfType<List>().FirstOrDefault(l => l.Title.Equals(DocumentLibName, StringComparison.CurrentCultureIgnoreCase));  
  21.               
  22.             context.Load(list);  
  23.             context.ExecuteQuery();  
  24.             //context.Load(items);  
  25.             context.Load(list.RootFolder);  
  26.             context.ExecuteQuery();  
  27.             context.Load(list.RootFolder.Folders);  
  28.             context.ExecuteQuery();  
  29.               
  30.             var folderName = Path.GetFileName("Your folder Name");  
  31.             var folder = list.RootFolder.Folders.OfType<Folder>().FirstOrDefault(t => t.Name == folderName);  
  32.             if (folder == null)  
  33.                 return;  
  34.             context.Load(folder);  
  35.              
  36.             context.ExecuteQuery();  
  37.             context.Load(  
  38.                 folder,  
  39.                 fields => fields.ListItemAllFields,  
  40.                 fields => fields.ListItemAllFields.HasUniqueRoleAssignments,  
  41.                 fields => fields.ListItemAllFields.RoleAssignments);  
  42.                 context.ExecuteQuery();              
  43.               
  44.             if (!folder.ListItemAllFields.HasUniqueRoleAssignments)  
  45.             {  
  46.                 folder.ListItemAllFields.BreakRoleInheritance(truetrue);  
  47.                 context.ExecuteQuery();  
  48.             }  
  49.   
  50.             Array.ForEach(accounts, account =>  
  51.             {  
  52.                 account =  account+"@"+<YourDomain>+".com";  
  53.                 try  
  54.                 {  
  55.                     web.EnsureUser(account);  
  56.                     var user = web.SiteUsers.OfType<User>().FirstOrDefault(u => u.LoginName.Equals(account, StringComparison.CurrentCultureIgnoreCase));  
  57.                     context.Load(user);  
  58.                     context.ExecuteQuery();  
  59.                     if (user != null)  
  60.                     {  
  61.                         var user_group = web.SiteUsers.GetByLoginName(user.LoginName);  
  62.                         folder.ListItemAllFields.RoleAssignments.GetByPrincipal(user_group).DeleteObject();  
  63.                         context.ExecuteQuery();  
  64.                     }                      
  65.                     var def = web.RoleDefinitions.GetByName("Read");  
  66.                     RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(context);  
  67.                     rdb.Add(def);  
  68.                     Principal usr = context.Web.EnsureUser(account);  
  69.                     folder.ListItemAllFields.RoleAssignments.Add(usr, rdb)  
  70.                       
  71.                 }  
  72.                 catch (Exception ex)  
  73.                 {  
  74.                     WriteLogMessage(ex.Message);  
  75.                     HandleError(ex);  
  76.                 }  
  77.   
  78.             });  
  79.             folder.Update();  
  80.             context.ExecuteQuery();  
  81.         }  
 As mentioned above, we secured the password using SecureString and here is the code for that:
  1. private static SecureString FetchPasswordFromConsole()  
  2.        {  
  3.            string password = System.Configuration.ConfigurationSettings.AppSettings["Password"].ToString();  
  4.            Console.WriteLine();  
  5.            var securePassword = new SecureString();                
  6.            foreach (char c in password)  
  7.                securePassword.AppendChar(c);  
  8.            securePassword.MakeReadOnly();  
  9.            return securePassword;  
  10.        }  

Hope this is useful.