Automate Removal of Orphan Users from SharePoint Online Using CSOM

If you had just migrated to SharePoint Online, one of the few things you will notice is that removing  a user from Azure Active Directory (AAD) does not automatically remove the user from SharePoint sites. This is by design, it is not a bug. This is to ensure that documents uploaded or created by those users are kept with their names in "Created By" field. So after removing them from AAD you have to go to each site the users have access to and manually remove them. But this poses a huge maintenance problem as you can't possibly keep up with this repetitive task, and even  knowing all the sites the user has access to poses a greater challenge. The best solution is to write a daemon application to handle such task.

If you already find yourself in this situation and need a solution, just copy and paste the code below in a console application:

We need to loop through a list of all AAD users and compare them with users in our SharePoint site collections. To get this list, add the following class to your project. I got this class from pnp sample project here. You will need to run some PowerShell script to give the necessary permission to your account to read from AAD. So be sure to click on the link for more instructions on how to do that.

Now update the App.config file with the following code:

Note: you will need to register an app in Azure to get a client Id and client secret.
That is all you need to do. Now you have the option of running this code as a scheduled task using webJob or run directly from Visual studio to delete orphan users from your site collections.

Hope you find it useful. Happy coding!

Comments

Popular posts from this blog

Generate Word Document From A SharePoint List Item Using Microsoft Flow

Calling Microsoft Graph API from an Angular 5 Single Page Application (SPA)

Creating SharePoint Framework Client Web Part and solving the challenges with _RequestDigest Token value using React