Deleting Azure Active Directory Users in C#

Using the Azure Active Directory with the official client Libraries is straighforward. Just
  1. Install the required libraries in your C# Project
    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory for authenticating yourself against the AD - and
    PM> Install-Package Microsoft.Azure.ActiveDirectory.GraphClient for accessing the directory
  2. Create your application in the directory
  3. Generate a ClientSecret for the Application
  4. Give permission to manager the AD to the Application
  5. Put it all together
See: for further assistance.


When it comes to deletion of objects (Users, Groups, etc.) it will become less easy, because the application you created has not enough permissions to delete objects. You might see the error

"Insufficient privileges to complete the operation."

This is caused by the setup of the application in the AD itself and the missing membership to the "Company Administrator"-Role.

See corresponding Issue on GitHub:

Solving Permission Problems

This can be done using the "Windows Azure Active Directory Module for Windows PowerShell". You might already heard of it, its the primary Tool of Office 365 Administrators. Download from:

"Question: Why is Azure Active Directory PowerShell separate from Azure PowerShell?
Answer: Azure Active Directory is used by all Microsoft online services including Microsoft Office 365. It pre-dates the current Azure PowerShell. In addition, Azure Active Directory does not currently leverage Azure Resource Management."

Use the following commands to change the membership of the application you just created

PM> Connect-MsolService

And login with a user from the Active Directory you are managing. Keep in mind that the used needs to be served by the directory itself, your MS-Account won't work.

Enumerate all Applications to find out the ObjectId (not displayed in the Portal, yet)

PS> Get-MsolServicePrincipal | ft DisplayName, AppPrincipalId, ObjectId -AutoSize

Note down the ObjectId of your application and used it in the following, last step to add the application itself to the "Company Administrators" Group

PS> Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId abcdef123-xxx-xxxx-xxxx-xxxxxxxxxxxx

Et voila!

Note: The PS-Scripts are not very chatty, no message means ok!


Popular posts from this blog

Home Assistant in Docker with Nginx and Let's Encrypt on Raspberry Pi

Use Bodmer TFT_eSPI Library with PlatformIO

Migrating from Arduino IDE to Visual Studio Code to PlatformIO