Search code examples
c#azure.net-coreazure-management-api

How to get total count of Active Directory users by using of Azure Mgmt SDK fluent


I am using https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent for getting resources in Azure with programmatically(C# .NET-Core Web app) and tried to get resources information by providing service principals as below....

string subscriptionId="XXX"; 
   AzureCredentials cred = new 
             AzureCredentialsFactory().FromServicePrincipal(UIConstants.ClientID, 
             UIConstants.Secret, UIConstants.Tenant,AzureEnvironment.AzureGlobalCloud);                      
            
    var azure = Azure.Configure()
                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) 
                     .Authenticate(cred) 
                     .WithSubscription(subscriptionId);

When I tried to get total numbers of count of Active Directory users like this:

int identity = azure.AccessManagement.ActiveDirectoryUsers.List().ToArray().Length;

I got this exception in code:

Operation returned an invalid status code 'Forbidden'

Please help me to fix above issue..

Thanks, Tutul


Solution

  • Azure resources like VM, storages are stored under the subscription. But AAD users are stored under directory.

    You need to assign the service principal a Directory readers role.

    Go to Azure Portal -> Azure Active Directory -> Roles and administrators -> Directory readers -> +Add assignments, enter the client id of the service principal.

    Now the service principal should have access to the Azure AD users.