Skip to content
Visual explainer 3h to learn 5 steps

Read directory data with Microsoft Graph

Query users and groups through Graph with the right permissions, consent, paging and throttling handling.

By Invicly Tech, , in Microsoft Entra & Microsoft 365 Administration. About 12 minutes to read.

Topic 26 of 31

In short

Microsoft Graph is the single web API in front of Microsoft Entra ID and Microsoft 365, so users, groups, sign-ins and licences can all be read with one kind of request. Every call needs a permission, granted either on behalf of a signed-in person (delegated) or to an app running on its own (application). A good reader asks for the smallest permission, pages through large results and backs off politely when Graph says it is busy.

Think of it like this: Graph is a library front desk: a delegated permission is a member borrowing with their own card, an application permission is the archive's own staff badge, and paging is collecting a long order one trolley at a time.

Explained simply

Most of what you click in the Entra and Microsoft 365 admin centres is stored behind one web API called Microsoft Graph. You send a request such as GET https://graph.microsoft.com/v1.0/users and get back JSON. Learning Graph means you can answer questions like who has no manager or which guests never signed in, without clicking through hundreds of pages.

Graph never trusts a request on its own. Each request carries a token, and the token lists permissions, also called scopes. User.Read.All lets you read every user. Group.Read.All lets you read groups. Anything with ReadWrite can change data, so ask for it only when you really need to change something.

There are two ways to hold a permission. With delegated permissions you sign in yourself, and Graph lets you do only what both the scope and your own admin role allow. With application permissions a script signs in as itself with a certificate or secret and gets the scope across the whole tenant. Application permissions always need an administrator to grant admin consent.

Big lists come back in pages. A response holds a value array and, if more remain, an @odata.nextLink URL. You keep calling that URL until it is gone. If you send too many requests, Graph answers 429 Too Many Requests with a Retry-After header saying how many seconds to wait. Patient scripts wait and try again.

Start safely in Graph Explorer, a free web tool that signs you in with delegated permissions. Use a lab or trial tenant, not production, and use read-only scopes until you understand the results.

Press Play on a diagram to walk through it one step at a time.

CompareDelegated versus application permissions
Delegated
  • A person signs in
  • Access is the overlap of the permission and that person's rights
  • Users or admins can consent, depending on the permission
  • Good for admin tools and Graph Explorer
Application
  • No person signs in
  • Access is whatever the permission allows, tenant-wide
  • Always needs admin consent
  • Good for scheduled jobs; guard the credential
SequenceReading every user, one page at a time
Script
Microsoft Graph
  1. 1GET /users?$select=id,displayName&$top=999
    Script to Microsoft Graph: GET /users?$select=id,displayName&$top=999
  2. 2200: value[...] plus @odata.nextLink
    Microsoft Graph to Script: 200: value[...] plus @odata.nextLink
  3. 3GET the nextLink URL exactly as given
    Script to Microsoft Graph: GET the nextLink URL exactly as given
  4. 4429 Too Many Requests, Retry-After: 10
    Microsoft Graph to Script: 429 Too Many Requests, Retry-After: 10
  5. 5Wait 10 seconds, send the same request again
    Script to Microsoft Graph: Wait 10 seconds, send the same request again
  6. 6200: last page, no nextLink, so stop
    Microsoft Graph to Script: 200: last page, no nextLink, so stop
FlowFrom first query to scheduled report
  1. 1
    Graph Explorer

    Try the query in a lab tenant

  2. 2
    PowerShell, delegated

    Connect-MgGraph with read scopes

  3. 3
    Add paging and $select

    Use -All and -Property

  4. 4
    App registration

    Certificate, application permission, admin consent

  5. 5
    Schedule and log

    Redacted logs with request-id

In depth

How effective access is worked out

For a delegated call, Graph checks two things: the scope in the token and the signed-in user's rights. The result is the overlap. A User Administrator holding a token with User.ReadWrite.All still cannot reset a Global Administrator's password, because the role does not allow it. That overlap is why delegated tools are safer for people doing interactive work.

For an application call there is no user, so the app gets the full reach of the granted application permission. User.ReadWrite.All as an application permission can edit any user in the tenant. Protect such apps like admin accounts: give them an owner, use a certificate or managed identity instead of a client secret where possible, and review their consent grants. Some APIs let you narrow application access further, for example Exchange application access policies or RBAC for applications, and Sites.Selected for SharePoint.

  • Delegated: scope AND user role
  • Application: scope only, tenant-wide
  • Prefer Read over ReadWrite, specific over Directory.*
  • Review grants in Entra admin center, Enterprise applications, Permissions
LayersWhat a delegated request must pass
  1. 1
    Token is valid

    Signed by Entra ID, not expired, right audience

  2. 2
    Scope present

    For example User.Read.All was consented

  3. 3
    User role allows it

    Directory role or ownership covers the target

  4. 4
    Licence or feature allows it

    For example sign-in logs via API need Entra ID P1 or P2

  5. 5
    Data returned

    Only the properties you asked for with $select

Consent: who can approve what

Consent is the record that a permission was approved. Low-risk delegated permissions such as User.Read (read your own profile) can be approved by users, if the tenant's user consent settings allow it. High-privilege delegated permissions and all application permissions need admin consent, given by a role such as Privileged Role Administrator, Cloud Application Administrator or Application Administrator, depending on the permission.

When you run Connect-MgGraph -Scopes the first time, you see a consent prompt for the Microsoft Graph Command Line Tools app. Granting it for your organisation applies to everyone who uses that app, so read the list before ticking the box. Many tenants turn off user consent and use the admin consent workflow, where users request access and a reviewer approves it.

  • User consent: only low-risk scopes, if allowed
  • Admin consent: tenant-wide, recorded on the service principal
  • Admin consent workflow lets users request instead of being blocked silently

Paging, $select and $filter

Large collections are paged. For users the default page size is 100 and $top can raise it to 999. Each page includes @odata.nextLink while more data remains. Treat that link as opaque: call it exactly, because it contains a skip token you must not edit.

Ask only for what you need. $select=id,displayName,userPrincipalName shrinks responses and avoids pulling personal data you have no reason to hold. $filter narrows results on the server, for example accountEnabled eq false. Some richer queries, such as $count or filtering on certain properties, are advanced queries that need the header ConsistencyLevel: eventual plus $count=true. In Graph PowerShell, -All follows nextLink for you, and -ConsistencyLevel eventual with -CountVariable handles the advanced case.

  • Default users page: 100; $top up to 999
  • Follow @odata.nextLink as given
  • $select reduces data and risk
  • Advanced queries: ConsistencyLevel eventual and $count

Throttling and quotas

Graph protects itself with limits per app, per tenant and per service. When you cross one, it returns HTTP 429 and usually a Retry-After header in seconds. The correct response is to wait that long and resend the same request. If there is no header, back off exponentially: 2, 4, 8 seconds and so on. The Microsoft Graph SDKs and the PowerShell SDK include a retry handler that already does this.

To avoid throttling, reduce calls rather than retrying harder. Use $select, filter on the server, use delta queries to fetch only changes since last time, and bundle up to 20 requests in one JSON batch call. Run large reports outside office hours and cache results you will read again.

  • 429 means wait, not fail
  • Honour Retry-After exactly
  • Batch up to 20 requests per $batch call
  • Delta queries fetch only what changed

Logs that do not leak

Admin scripts are often run again months later, so their logs become evidence. Make them useful and safe. Record the request path, status code, request-id header, item counts and timings. Do not record bearer tokens, client secrets, full response bodies or personal fields you did not need. If you must identify a person, log the object ID rather than the name and email.

The request-id and client-request-id values let Microsoft support find your call if something goes wrong, so they are worth keeping. Store logs where only admins can read them, and set a retention period that matches your organisation's policy.

  • Keep: path, status, request-id, counts, time
  • Drop: tokens, secrets, full bodies
  • Prefer object IDs over names in logs

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Use Graph Explorer~35m
  2. 2
    Pick delegated or app permissions~35m
  3. 3
    Grant admin consent~35m
  4. 4
    Page through results~35m
  5. 5
    Handle throttling~35m

Key points

  • Pick the narrowest permission that does the job: User.Read.All to read users, not Directory.ReadWrite.All.
  • Delegated access can never exceed what the signed-in admin could do in the portal; application access can.
  • Admin consent is a tenant-wide grant. Review who granted what under Enterprise applications.
  • Follow @odata.nextLink until it disappears; never build page URLs yourself.
  • On HTTP 429, wait for the Retry-After value, then retry. The Graph SDKs do this for you.

Key terms

Tap a card to flip it. 0/6 known

Examples

powershell
# Read-only session with the smallest scopes needed
Connect-MgGraph -Scopes 'User.Read.All','Group.Read.All'
(Get-MgContext).Scopes   # confirm what the token holds

# -All follows @odata.nextLink for you
$users = Get-MgUser -All -Property Id,DisplayName,UserPrincipalName,AccountEnabled |
  Select-Object Id,DisplayName,UserPrincipalName,AccountEnabled
$users.Count

Disconnect-MgGraph

Read all users with delegated, read-only scopes, then sign out.

Find disabled accounts that still hold licences

Prerequisites: Graph PowerShell installed (Install-Module Microsoft.Graph -Scope CurrentUser) and a lab tenant. The script reads only. Expected evidence: a CSV listing object IDs and licence counts. Cleanup: Disconnect-MgGraph and delete the CSV when the review is done.

powershell
Connect-MgGraph -Scopes 'User.Read.All'
$disabled = Get-MgUser -All -Filter 'accountEnabled eq false' `
  -Property Id,UserPrincipalName,AssignedLicenses
$disabled |
  Where-Object { $_.AssignedLicenses.Count -gt 0 } |
  Select-Object Id,UserPrincipalName,@{n='Licences';e={$_.AssignedLicenses.Count}} |
  Export-Csv .\disabled-with-licences.csv -NoTypeInformation
Disconnect-MgGraph

Handle paging and throttling with raw requests

Sometimes you need the raw REST call, for example for a beta property. Invoke-MgGraphRequest reuses your Graph session. This loop follows nextLink and waits when it gets a 429. In real runs the SDK retries for you; the loop shows what that means.

powershell
$uri = 'https://graph.microsoft.com/v1.0/groups?$select=id,displayName&$top=999'
$all = @()
while ($uri) {
  try {
    $page = Invoke-MgGraphRequest -Method GET -Uri $uri
    $all += $page.value
    $uri = $page.'@odata.nextLink'
  } catch {
    $wait = $_.Exception.Response.Headers.RetryAfter.Delta.TotalSeconds
    if (-not $wait) { throw }
    Start-Sleep -Seconds $wait
  }
}
"Groups: $($all.Count)"

Quick reference

  • Connect-MgGraph -Scopes 'User.Read.All' starts a delegated session with one scope.
  • (Get-MgContext).Scopes shows the permissions your current token holds.
  • Get-MgUser -All follows @odata.nextLink; without -All you get the first page only.
  • Delegated access = scope AND the signed-in user's role. Application access = scope only.
  • HTTP 429: wait Retry-After seconds, then resend. Never hammer.
  • Use $select (or -Property) to fetch only the fields you need.
  • Advanced queries need ConsistencyLevel: eventual and $count=true.
  • Graph Explorer: developer.microsoft.com/graph/graph-explorer

Common mistakes

  • Granting Directory.ReadWrite.All or an application permission because a forum post said so, when a read-only delegated scope was enough.
  • Reading only the first page and reporting 100 users when the tenant has 1,400.
  • Logging full responses or tokens, which spreads personal data and secrets into log files.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A scheduled script runs at night with nobody signed in. Which permission type does it need?

Question 2

2Your first call returns 100 users and an @odata.nextLink. What does that mean?

Question 3

3Which is the narrowest permission for listing users' names and UPNs?

Question 4

4Graph returns 429 with Retry-After: 30. What is the right response?

Question 5

5What should a redacted admin log keep?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    In Graph Explorer, signed in to a lab tenant, list users showing only displayName and userPrincipalName. Then open the Modify permissions tab and note which permission the call needed.

  2. Exercise 2medium

    Write a PowerShell command that counts all guest users using an advanced query, without downloading every user.

  3. Exercise 3hard

    Design the permissions for a nightly job that reports group memberships to a CSV. Say which app type, permission, credential and log fields you would use, and how you would prove it cannot change data.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a paid licence to use Microsoft Graph?
No, Graph itself is free to call. Some data behind it needs licences, for example reading sign-in logs through the API needs Microsoft Entra ID P1 or P2 in the tenant.
Should I still use the AzureAD or MSOnline PowerShell modules?
No. Both are retired. Use the Microsoft Graph PowerShell SDK (the Microsoft.Graph module) instead.
What is the difference between v1.0 and beta?
v1.0 is the supported, stable API for production scripts. Beta has newer features that can change or disappear, so avoid it for anything you rely on.
Why does Graph Explorer show data I did not expect to see?
It uses your own account with delegated permissions, so it shows what your role can see. Use a lab tenant and a non-admin test account to check what normal users see.

Go deeper

ShareXLinkedInWhatsApp