Get list all Users from Azure AD

846 views Asked by At

I'm trying to get list of all users from Azure Active Directory using the below code, but still I'm getting only 100 records at one time.
I'm using DOTNET Core version 7

var scopes = new string[] { "https://graph.microsoft.com/.default" };

var confidentialClient = ConfidentialClientApplicationBuilder
                    .Create(ClientId)
                    .WithAuthority($"https://login.microsoftonline.com/" + TenantId + "/v2.0")
                    .WithClientSecret(ClientSecret)
                    .Build();

GraphServiceClient graphServiceClient =
                    new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                    {

                        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                        var authResult = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

                        // Add the access token in the Authorization header of the API
                        requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    })
                    );
var users = await graphServiceClient.Users.Request().GetAsync();

I want to get all the users from Azure AD.

I tried this line of code:

var users = await graphServiceClient.Users.Request().GetAsync();

but I'm getting only 100 records, there are about 1500 records in Azure AD, I want to get all those records.

2

There are 2 answers

3
RithwikBojja On

I do agree with @Dai, you need to supply range, Or you can use Top() Operator in your code like:

 var users = await graphServiceClient.Users.Request().Top(500).GetAsync();

Alternatively you can use below code which I followed from SO-thread and GithubDoc:

using Microsoft.Graph;
using Microsoft.Identity.Client;
using Microsoft.Kiota.Abstractions.Authentication;


string rithClientId1 = "7436259214846792e";
string rithClientSecret1 = "0L68Qd0Jmpbanh";
string rithscopes = "https://graph.microsoft.com/.default";
IConfidentialClientApplication rithapp = ConfidentialClientApplicationBuilder
    .Create(rithClientId1)
    .WithClientSecret(rithClientSecret1)
    .WithAuthority(new Uri("https://login.microsoftonline.com/2773-d343-4afe735719f9b0b/oauth2/v2.0/token"))
    .Build();
var authResult1 = await rithapp.AcquireTokenForClient(new string[] { rithscopes }).ExecuteAsync();
string rithaccessToken = authResult1.AccessToken;

String authorizationToken = rithaccessToken;
string token = authorizationToken.ToString().Replace("Bearer ", "");
TokenProvider provider2 = new TokenProvider();
provider2.token = token;
var authenticationProvider1 = new BaseBearerTokenAuthenticationProvider(provider2);
var graphServiceClient1 = new GraphServiceClient(authenticationProvider1);
var user = await graphServiceClient1.Users.GetAsync();
foreach (var us in user.Value)
{
    Console.WriteLine($"User: {us.DisplayName} ({us.UserPrincipalName})");
}


public class TokenProvider : IAccessTokenProvider
{
    public string token { get; set; }
    public AllowedHostsValidator AllowedHostsValidator => throw new NotImplementedException();

    public Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
    {
        return Task.FromResult(token);
    }
}

Output:

enter image description here

0
Gaurav Mantri On

When requesting the list of users using Graph API, a single request only returns a maximum of 100 items in the result. If there are more items, then a continuation token is also returned in the result. What you have to do is make use of this continuation token to make additional requests.

Please try something like the following:

var scopes = new string[] { "https://graph.microsoft.com/.default" };

var confidentialClient = ConfidentialClientApplicationBuilder
                    .Create(ClientId)
                    .WithAuthority($"https://login.microsoftonline.com/" + TenantId + "/v2.0")
                    .WithClientSecret(ClientSecret)
                    .Build();

GraphServiceClient graphServiceClient =
                    new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                    {

                        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                        var authResult = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

                        // Add the access token in the Authorization header of the API
                        requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    })
                    );

var users = new List<User>();
var request = graphServiceClient.Users;

do
{
    var result = await request.GetAsync();
    nextLink = result.OdataNextLink;
    users.AddRange(result.Value);
    if (nextLink == null) break;
    request = new UsersRequestBuilder(nextLink, graphServiceClient.RequestAdapter);
} while (true);

// do something with "users" list...