Search code examples
microsoft-graph-apiazure-ad-b2c

How do you (quickly) count AAD B2C users?


We're trying to count the number of user objects in a B2C tenant, which is somewhat large. When it was small, the simple/obvious hack of just reading all the users worked easily and quickly.

Get-AzADUser | Measure-Object

Now this takes an absurd amount of time (30+ mins, and wastes AAD processing, network bandwidth, etc). Handily, the Graph API includes an endpoint to request the number of objects! Hooray! ;) https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-beta&tabs=http#example-6-get-only-a-count-of-users

Connect-AzAccount
Set-AzContext -Tenant <your 'normal' AAD tenant>
$AzToken = Get-AzAccessToken -ResourceUrl https://graph.microsoft.com

Invoke-RestMethod -Method Get -Authentication Bearer -Token (ConvertTo-SecureString -AsPlainText -Force -String $AZAccess.Token) -Headers @{ConsistencyLevel = 'eventual'} -Uri https://graph.microsoft.com/beta/users/`$count

1234

But! When using this method to attempt to find how many B2C accounts we have:

Connect-AzAccount
Set-AzContext -Tenant <your 'B2C' AAD tenant>
$AzToken = Get-AzAccessToken -ResourceUrl https://graph.microsoft.com

Invoke-RestMethod -Method Get -Authentication Bearer -Token (ConvertTo-SecureString -AsPlainText -Force -String $AZAccess.Token) -Headers @{ConsistencyLevel = 'eventual'} -Uri https://graph.microsoft.com/beta/users/`$count

Invoke-RestMethod: {"error":{"code":"Request_BadRequest","message":"$count is not currently supported.","innerError":{"date":"2021-04-29T07:06:09","request-id":"xxx","client-request-id":"xxx"}}}

So, how do you count users in a large B2C tenant?


Solution

  • There is now a somewhat new answer from Microsoft, since June-2023-ish.

    https://learn.microsoft.com/en-us/azure/active-directory-b2c/tenant-management-directory-quota

    Their page has some instructions to create an application registration, but the most important parts are (paraphrased):

    1. For your app to call Microsoft Graph API ... grant Organization.Read.All permission
    2. GET 'https://graph.microsoft.com/beta/organization?$select=directorySizeQuota'
    3. The result is a count of all AAD objects; these objects include user accounts, app registrations, groups, etc

    Results:

    {
        "@odata.context": "https://graph.microsoft.com/beta/$metadata#organization(directorySizeQuota)",
        "value": [
            {
                "directorySizeQuota": {
                    "used": 211802,
                    "total": 50000000
                }
            }
        ]
    }