2 minute read

When managing users in Azure Active Directory (AD), you often need to retrieve updated information about active users whose accounts are still enabled. This task can be easily handled using the Microsoft Graph API. In this blog post, I’ll show you how to do that with a simple asynchronous method in C#.

What This Code Does:

  • Asynchronous programming: It handles tasks without blocking the main thread.
  • Delta query: Only gets users that have changed since the last query, which saves time and resources.
  • Pagination: Handles large data sets by retrieving data page by page.
  • Logging: Tracks progress and errors using a logging tool.
The Code
public async Task<List<string>> GetUpdatedLoginEnabledUsers()
{
    var getUpdatedLoginEnabledUsers = new List<string>();
    var currentPageCount = 0;
    Log.Information("Fetching active users from Azure AD...");
    
    try
    {
        var graphClient = GetGraphServiceClient(); // Initialize the Graph client
        var response = await graphClient.Users.Delta()
            .Request().Top(500) // Get the first 500 users
            .Filter("Usertype eq 'Member' and AccountEnabled eq true") // Filter for active members
            .GetAsync();
        
        currentPageCount += response.CurrentPage.Count;
        
        if (response.CurrentPage.Count > 0)
        {
            // Add the IDs of active users to the list
            getUpdatedLoginEnabledUsers.AddRange(response.CurrentPage.Select(s => s.Id));
            
            // Check if there are more pages of data and keep fetching
            while (response.NextPageRequest != null)
            {
                response = await response.NextPageRequest.GetAsync();
                currentPageCount += response.CurrentPage.Count;
                
                if (response.CurrentPage.Count > 0)
                {
                    getUpdatedLoginEnabledUsers.AddRange(response.CurrentPage.Select(s => s.Id));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Log.Error(ex, "Error occurred while fetching users from Azure AD.");
    }

    Log.Information("{0} active users found", currentPageCount);
    return getUpdatedLoginEnabledUsers;
}
Explanation of the Code
  1. Graph Client Initialization: We start by creating a GraphServiceClient to connect to the Microsoft Graph API. This client allows us to make requests to Azure AD.

  2. Delta Query: The Users.Delta() query fetches only the users who have been updated since the last time we checked. This makes the process more efficient by retrieving only the changes instead of the entire user list.

  3. Filtering for Active Users: We use a Filter() to ensure that only users whose Usertype is 'Member' and whose AccountEnabled is true (i.e., active users) are returned.

  4. Handling Multiple Pages: Sometimes, the API returns results in multiple pages, especially when there are many users. We check for the NextPageRequest to fetch the next batch of users and keep adding them to our list until all pages are processed.

  5. Logging: To keep track of the process, we use a logging system (Serilog, in this case). It logs when the fetching process starts, how many users are found, and any errors that occur.

  6. Error Handling: The try-catch block ensures that if something goes wrong (like a network issue or API failure), the error will be logged, making it easier to debug.

Why This Approach Works Well

  • Efficiency: By using delta queries, we’re only fetching the users that have been updated, which saves bandwidth and speeds up the process.
  • Asynchronous Execution: The use of async and await allows the system to keep running other tasks while waiting for the API response.
  • Pagination: This ensures that even if there are many users, the system won’t overload. It fetches data in smaller chunks.

Conclusion

This method provides a simple and effective way to retrieve updated, active users from Azure AD. It’s efficient, handles large datasets well, and keeps everything running smoothly with asynchronous programming and proper error handling.

If you’re working with Azure AD, this approach can help you keep your user data up-to-date while minimizing the load on your system. Give it a try in your next project!

Leave a comment