Microsoft 365 – Governance implementation – Exporting All External Users in Tenant Using .NET Core and MS Graph APIs

Exporting All External Users in Tenant Using .NET Core and MS Graph APIs

“When you change your thoughts, remember to also change your world.”

Greetings, Microsoft 365 Navigators!

Embark on a journey with .NET Core and Microsoft Graph APIs to explore and export external users within your Microsoft 365 domain. In the realm of collaborative environments, understanding and managing external users are crucial. Let’s delve into a real-world scenario and empower ourselves with the tools needed for enhanced security, streamlined user management, and compliance.

Key Takeaways from this article

  • Learn to export external users from Microsoft 365 using a .NET Core app and Microsoft Graph APIs.
  • Understand the real-world significance of managing external users for security, compliance, and efficient collaboration.
  • Gain insights into prerequisites, including Microsoft 365 and Microsoft Entra ID access, and the .NET Core SDK.
  • Explore a scenario where IT administrators efficiently manage external user landscapes.
  • Discover the need for security compliance, efficient user management, and audit and reporting.
  • The .NET Core application utilizes Microsoft Graph APIs for fetching and exporting external user data.
  • Strategic guide on Graph API permissions, emphasizing the least privilege principle and best practices.
  • Step-by-step guide, including authentication, fetching external users, and exporting to Excel.
  • Code deep dive explaining the event handler, authentication, fetching, checking, and exporting external user data.
  • Emphasize the strategic approach to Graph API permissions, considering user read permissions, application permissions, and permission assignment best practices.

Prerequisites

To embark on this journey, we need to ensure that we are well-prepared. Here are the prerequisites:

  • Microsoft 365 Account: Ensure we have a valid Microsoft 365 account with the necessary permissions.
  • Microsoft Entra ID Access: We require access to Microsoft Entra ID for application registration and obtaining authentication credentials.
  • .NET Core SDK: It’s essential to have the latest version of the .NET Core SDK installed on our development machine.

Real-World Example: Navigating External User Insights with .NET Core and Microsoft Graph

In the dynamic landscape of collaborative work environments, understanding and managing external users is paramount. Let’s delve into a real-world scenario to grasp the practical significance of exporting external users from Microsoft 365 using a .NET Core application and Microsoft Graph.

Scenario:

Imagine you are an IT administrator responsible for overseeing user access and collaboration within your organization’s Microsoft 365 environment. Your organization frequently collaborates with external partners, vendors, or clients who are granted access as guest users.

The challenge arises in efficiently managing and comprehending the landscape of these external users. Security audits, compliance checks, and streamlined user management are essential components of maintaining a secure and collaborative environment.

Why Do We Need This?

Security Compliance:

  • Ensure that external users align with security and compliance policies.
  • Regularly audit and verify external user access for adherence to security standards.

Efficient User Management:

  • Streamline user management processes by having an overview of external users.
  • Quickly identify and manage access for external users, ensuring optimal collaboration.

Audit and Reporting:

  • Facilitate security audits by exporting detailed reports on external user activities.
  • Generate insights into external user interactions, aiding in compliance reporting.

Benefits:

Granular Security Oversight:

  • Identify and address security risks associated with external user access.
  • Ensure that external users only have access to the necessary resources.

Streamlined User Administration:

  • Simplify user administration by having a centralized list of external users.
  • Easily revoke or modify access based on the exported insights.

Proactive Compliance Management:

  • Proactively manage compliance by regularly exporting and reviewing external user data.
  • Demonstrate adherence to compliance standards through comprehensive reporting.

Application

The .NET Core application provided here leverages Microsoft Graph APIs to fetch and export all external users in the Microsoft 365 tenant. The code utilizes the Graph SDK to interact with the Microsoft Graph service.

Graph API Permissions: A Strategic Approach

  • Before your .NET Core application can seamlessly interact with Microsoft Graph API, it needs the appropriate permissions.
  • This ensures that your application can access the required resources and perform specific actions. Grant the following permissions in the Azure portal to enable comprehensive functionality:

Grant Permissions

When integrating Microsoft Graph API into your .NET Core application to export external users, selecting the appropriate permissions is a critical step. Here’s a strategic guide on the necessary permissions to ensure a seamless and secure operation:

  • User Read Permissions:
    • Permission Type: Delegated
    • Permission Name: User.Read
    • Explanation: This permission is essential for fetching user details, including external users. It allows the application to read basic user profile information.
  • Directory.Read.All:
    • Permission Type: Delegated
    • Permission Name: Directory.Read.All
    • Explanation: This permission grants the application the ability to read data in the organization’s directory, which includes information about external users.
  • User.ReadWrite.All:
    • Permission Type: Delegated
    • Permission Name: User.ReadWrite.All
    • Explanation: While read permissions are necessary, having the ability to also write user data can be beneficial for certain scenarios. Exercise caution and grant this permission only if needed.
  • Application Permissions:
    • Permission Type: Application
    • Permission Name: User.Read.All
    • Explanation: Application permissions are required when specific actions need to be performed without a signed-in user. In this case, reading all users’ information is necessary.
  • Policy.Read.All:
    • Permission Type: Delegated
    • Permission Name: Policy.Read.All
    • Explanation: This permission is crucial for scenarios where policies, such as access or security policies, need to be retrieved. It ensures comprehensive insights into external user access policies.

Permission Assignment Best Practices:

  • Least Privilege Principle: Only grant the permissions that are absolutely necessary for the application’s functionality. Avoid unnecessary permissions that might expose sensitive information.
  • Regular Permission Reviews: Conduct periodic reviews of the assigned permissions. As the application evolves, ensure that the permissions align with the current functionalities to maintain the principle of least privilege.
  • Consistent Logging and Monitoring: Implement robust logging and monitoring mechanisms to track the usage of permissions. This facilitates early detection of any unauthorized access or unusual activities.
  • Utilize Azure AD Roles: Leverage Azure AD roles for fine-grained access control. Assign roles based on specific responsibilities, reducing the risk of over-privileged accounts.

By carefully selecting and configuring these permissions, your application can interact with Microsoft Graph API securely and efficiently. Always prioritize the principle of least privilege and stay informed about updates to Microsoft Graph API permissions to maintain a robust security posture.

Step-by-Step Guide

  1. Authentication: Obtain an authenticated instance of the Graph client using the registered application’s credentials.
  2. Fetch External Users: Use the Graph client to fetch users filtered by user type, specifically targeting ‘Guest’ users.
  3. Export to Excel: Convert the fetched external user data into a structured format and export it to an Excel file.

Code Deep Dive: Exporting External Users in .NET Core with Microsoft Graph

private async void OnExportExternalUsersToExcelClick(object sender, RoutedEventArgs e)
{
try
{
// Get the authenticated Graph client
var graphClient = await _graphService.GetAuthenticatedGraphClient();

    // Fetch external/guest users from Azure AD
    var externalUsersResponse = await graphClient.Users
       .GetAsync((requestConfiguration) =>
       {
           // Filter to get the User Information List
           requestConfiguration.QueryParameters.Filter = "userType eq 'Guest'";
       });

    var externalUsers = externalUsersResponse.Value;

    if (externalUsers != null)
    {
        List<ExternalUserSiteDto> externalUserSites = new List<ExternalUserSiteDto>();

        // Iterate through external users
        foreach (var externalUser in externalUsers)
        {
            var userPrincipalName = externalUser.UserPrincipalName;

            // Assuming 'DisplayName' is the correct field, modify if needed
            var isExternalUser = userPrincipalName.Contains("#EXT#");

            if (isExternalUser)
            {
                externalUserSites.Add(new ExternalUserSiteDto
                {
                    UserId = externalUser.Id,
                    UserName = userPrincipalName,
                    Site = "N/A" // Modify as per your requirement
                });
            }
        }

        // Export external user sites to Excel
        ExportToExcel(externalUserSites, "ExternalUserSites");
    }
}
catch (Exception ex)
{
    ResultTextBox.Text += $"Error: {ex.Message}\n";
}

}

Line-by-Line Explanation:

Event Handler Definition:

private async void OnExportExternalUsersToExcelClick(object sender, RoutedEventArgs e)

  • This method is an event handler triggered when a specific UI element, like a button, is clicked. The async void signature indicates that it can perform asynchronous operations.

Authentication and Graph Client Initialization:

var graphClient = await _graphService.GetAuthenticatedGraphClient();

  • This line obtains an authenticated instance of the Graph client using the _graphService.GetAuthenticatedGraphClient() method. The await keyword ensures that authentication completes before proceeding.

Fetching External Users:

var externalUsersResponse = await graphClient.Users
.GetAsync((requestConfiguration) =>
{
// Filter to get the User Information List
requestConfiguration.QueryParameters.Filter = "userType eq 'Guest'";
});

var externalUsers = externalUsersResponse.Value;

  • These lines fetch external/guest users from Azure AD using the Microsoft Graph API. The Filter is used to narrow down the results to users with the user type ‘Guest.’

Checking External Users and Creating a List:

if (externalUsers != null)
{
List externalUserSites = new List();

  • This conditional check ensures that there are external users before proceeding. It initializes a list of ExternalUserSiteDto objects, which will hold information about external users and their associated sites.

Iterating Through External Users:

foreach (var externalUser in externalUsers)
{
var userPrincipalName = externalUser.UserPrincipalName;

// Assuming 'DisplayName' is the correct field, modify if needed
var isExternalUser = userPrincipalName.Contains("#EXT#");

if (isExternalUser)
{
    externalUserSites.Add(new ExternalUserSiteDto
    {
        UserId = externalUser.Id,
        UserName = userPrincipalName,
        Site = "N/A" // Modify as per your requirement
    });
}

}

  • This loop iterates through each external user fetched from Azure AD. It checks if the user’s principal name contains “#EXT#”, assuming it indicates an external user. If true, it adds the user’s information to the externalUserSites list.

Exporting External User Sites to Excel:

ExportToExcel(externalUserSites, "ExternalUserSites");

  • After gathering information about external users and their associated sites, this line calls the ExportToExcel method to export the data to an Excel file. The method takes the list of ExternalUserSiteDto objects and a string identifier (“ExternalUserSites”).

Error Handling:

} catch (Exception ex) {
ResultTextBox.Text += $"Error: {ex.Message}\n";
}

  • In case of any exceptions during the process, an error message is appended to the ResultTextBox for user feedback.

This code provides a structured approach to fetch external users, filter them based on certain criteria, and export relevant information to Excel, making it a valuable tool for user management and analysis.

We have very good / detailed articles on Microsoft Graph. Kindly please have a look. – https://knowledge-junction.in/category/technology-articles/m365/microsoft-graph/

Conclusion

Exporting all external users from our Microsoft 365 tenant provides a valuable resource for user management, security, and compliance. By leveraging .NET Core and Microsoft Graph APIs, we can efficiently obtain, analyze, and report on external user data. This approach empowers us with the tools needed to enhance security, streamline user management, and meet compliance requirements.

Also get my article updates on my social media handles.

Twitter – https://twitter.com/PrajyotYawalkar?t=oovP0r9FnDtz5nNSJGKO0Q&s=09

LinkedIn – https://www.linkedin.com/in/prajyot-yawalkar-093716224/

Have a wonderful day.

Thanks for reading.

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Microsoft 365

Subscribe now to keep reading and get access to the full archive.

Continue reading