Guest User

Untitled

a guest
Aug 31st, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.62 KB | None | 0 0
  1. using Microsoft.Online.SharePoint.TenantAdministration;
  2. using Microsoft.SharePoint.Client;
  3. using OfficeDevPnP.Core.Entities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Security;
  8. using System.Threading.Tasks;
  9. using Microsoft.Azure.ActiveDirectory.GraphClient;
  10. using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
  11. using Microsoft.Azure;
  12.  
  13. namespace SPUserRemover
  14. {
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. try
  20. {
  21. //App-Only authentication does not work for SiteEntity
  22. var password = new SecureString();
  23. string userName = CloudConfigurationManager.GetSetting("UserName");
  24. string Mypassword = CloudConfigurationManager.GetSetting("Password");
  25. string tenantAdminUrl= CloudConfigurationManager.GetSetting("TenantAdminUrl");
  26. foreach (char c in Mypassword.ToCharArray()) password.AppendChar(c);
  27. var credentials = new SharePointOnlineCredentials(userName, password);
  28. ActiveDirectoryClient azureClient = AzureAdAuthentication.GetActiveDirectoryClientAsApplication();
  29. var aadUsers = GetUsers(azureClient);
  30. using (var clientContext = new ClientContext(tenantAdminUrl))
  31. {
  32. clientContext.Credentials = credentials;
  33. Tenant tenant = new Tenant(clientContext);
  34. var prop = tenant.GetSiteCollections(0, 300, true, true);
  35. clientContext.ExecuteQuery();
  36.  
  37. ClientContext context = null;
  38. foreach (SiteEntity sp in prop)
  39. {
  40. context = new ClientContext(sp.Url);
  41. context.Credentials = credentials;
  42. Web web = context.Web;
  43. UserCollection usercollection = web.SiteUsers;
  44. context.Load(usercollection, usercols=>usercols.Include(userCol=>userCol.LoginName, userCol => userCol.Id));
  45. context.ExecuteQuery();
  46. foreach (Microsoft.SharePoint.Client.User user in usercollection)
  47. {
  48.  
  49. string spUserLoginName = "";
  50. //Check if an account is a user account or not
  51. var isUserAccount = user.LoginName.Contains("i:0#.f|membership|");
  52. if(isUserAccount )
  53. {
  54. spUserLoginName = DecodeClaim(clientContext, user.LoginName);
  55. }
  56.  
  57. var userExist = aadUsers.Result.Contains(spUserLoginName.ToLower());
  58.  
  59. //if account is not in aad but exists on sp and it is an sp user, remove it.
  60. if (!userExist && spUserLoginName != "")
  61. {
  62.  
  63. web.SiteUsers.RemoveById(user.Id);
  64. web.Update();
  65. }
  66.  
  67. }
  68.  
  69. context.ExecuteQuery();
  70. }
  71.  
  72.  
  73. // Console.ReadLine();
  74.  
  75.  
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. Console.WriteLine(ex);
  81. }
  82. }
  83.  
  84.  
  85. //Decode encoded loginName i.e. strip the loginName of token i:0#.f|membership|
  86. public static string DecodeClaim(ClientRuntimeContext context, string encodedLoginName)
  87. {
  88. var tenant = new Tenant(context);
  89. var clientResult = tenant.DecodeClaim(encodedLoginName);
  90. context.ExecuteQuery();
  91. return clientResult.Value;
  92. }
  93.  
  94.  
  95. //Set the client Secret and Id to authenticate to AD.
  96. //You will need to give permission to read Azure directory using the following powershell commands
  97. //## Connect to the Microsoft Online tenant
  98. // Connect-MsolService
  99.  
  100. //## Set the app Client Id, aka AppPrincipalId, in a variable
  101. //$appId = "9a329aa2-01de-4248-8dc4-3187ed7e1c6c"
  102.  
  103. //## get the App Service Principal
  104. //$appPrincipal = Get-MsolServicePrincipal -AppPrincipalId $appId
  105.  
  106. //## Get the Directory Readers Role
  107. //$directoryReaderRole = Get-MsolRole -RoleName "Directory Readers" ##get the role you want to set
  108.  
  109. //##Give the app the Directory Reader role
  110. //Add-MsolRoleMember -RoleMemberType ServicePrincipal -RoleObjectId $directoryReaderRole.ObjectId -RoleMemberObjectId $appPrincipal.ObjectId
  111.  
  112. //##Confirm that the role has our app
  113. //Get-MsolRoleMember -RoleObjectId $directoryReaderRole.ObjectId
  114. private static async Task<List<string>> GetUsers(ActiveDirectoryClient azureClient)
  115. {
  116. List<IUser> Iusers = new List<IUser>();
  117. IPagedCollection<IUser> pagedCollection = await azureClient.Users.ExecuteAsync();
  118.  
  119. if (pagedCollection != null)
  120. {
  121. do //append pages to the list
  122. {
  123. Iusers.AddRange(pagedCollection.CurrentPage.ToList());
  124. pagedCollection = await pagedCollection.GetNextPageAsync();
  125. } while (pagedCollection != null && pagedCollection.MorePagesAvailable);
  126. }
  127.  
  128. List<string> users = new List<string>();
  129. foreach (var user in Iusers)
  130. {
  131. users.Add(user.UserPrincipalName.ToLower());
  132. }
  133.  
  134. return users;
  135. }
  136. }
  137.  
  138. }
Add Comment
Please, Sign In to add comment