Search code examples
pythonpython-3.xazure-active-directoryazure-cli

How to fetch Azure Active Directory User Details using Azure CLI


I have a requirement where I need to fetch the count of users, user names for a given active directory group. For ex, If AAD Group A had 2 members, B & C, I need to get both the user details.

Just a few days back, I was logging to Azure using my organization email id and password would be access token and it would work perfectly fine:

az account get-access-token --resource "https://cognitiveservices.azure.com"

az login --username {user_name} --tenant {tenant_id} --password {access_token}

az ad group member list --group {AAD_group_name}

Since access token expires every 1 hour, I would get the new token programatically and get the AAD user details.

enter image description here

But when I run the 2nd step now, I get an error: RuntimeError: WsTrust server returned error in RSTR: {'reason': 'ID3242: The security token could not be authenticated or authorized.', 'code': 'a:FailedAuthentication'}

enter image description here

Is there any other alternative where AZ CLI can talk to AAD and get the details? Because I tried with SPN as well but it says:

Insufficient privileges to complete the operation.

enter image description here

I want to get AAD group details using Azure CLI


Solution

  • Depending on the version of Azure CLI you are using there is a feature gap where service principals are not listed as group members. As a workaround you can use az rest to call the beta API: https://docs.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-beta&tabs=http

    See related issues: Q&A Github

    In Powershell you can use Get-AzureADGroupMember

    To list all group members:

    Get-AzureADGroup -ObjectId df095002-f3ae-9077-6720-3a095edd8ff4 | Get-AzureADGroupMember -All $True 
    

    To list the top 50 members:

    Get-AzureADGroup -ObjectId df095002-f3ae-9077-6720-3a095edd8ff4 | Get-AzureADGroupMember -Top 50 
    

    Edit: Make sure to connect to the tenant before running the commands using Connect-Azuread -TenantID <your tenantid>