The task is simple. Lets imagine you want to count all current users in your Azure AD B2C. The tricky part - you want to use Azure CLI to accomplish this. The problem here is not the command to get the count. The problem is how to authorize your terminal session to. Lets begin with Azure CLI. The “normal” approach would be something like:
This will open a browser where you can authorize yourself. Then after returning to the shell you would try something like
az account set -s SUBSCRIPTIONID
which obviously cannot work because you can’t have a subscription in a B2C-tenant.
The solution is to not use
az account. Instead you should do
az login --tenant TENANTURL_OR_ID --allow-no-subscriptions
This will again let you authorize yourself in the browser and afterwards you can perform something like
az ad user list --query " | length(@)"
to retrieve the amount of users or
az ad app list --query " | length(@)"
for the amount of app registrations.
If you are using
az login using the browser-auth you’re probably doing something wrong from the security perspective. The point is here, that your personal account is used. If you happen to be a global admin this is very bad practice.
The alternative is to create a service account with
az ad sp create-for-rbac --name ServicePrincipalName --role Contributor
The output will show you the client id and password of the newly created service principal. You keep track and use them in
az login --service-principal --username APP_ID --password PASSWORD --tenant TENANT_ID
--allow-no-subscriptions for B2C again.
The “perfect” way would be that you pre-created service principals during your governance-setup of Azure and store the passwords in a central Azure KeyVault. Then give read-access to these secrets (you would normally create several RBAC SPs for different scopes like one for every management group) to the personal accounts of your co-admins. Whenever you need to manage a resource you simply use the SP.
The equivalent command for Powershell Az module would be
Connect-AzAccount -Tenant $TENANTURL_OR_ID
The service principal version would be
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPassword Connect-AzAccount -ServicePrincipal -TenantId $TENANTURL_OR_ID -Credential $credential