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: http://justazure.com/azure-active-directory-part-5-graph-api/ for further assistance.

But

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: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/5

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: https://msdn.microsoft.com/en-us/library/jj151815.aspx

"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."
Source: http://blogs.technet.com/b/ad/archive/2016/01/08/azure-ad-mailbag-powershell-tips-and-tricks.aspx

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!

Comments

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