Search code examples
c#azure-active-directory.net-8.0asp.net-core-8

Fetch employee id from from job description properties .NET 8


I am trying to fetch Employee ID field from Azure EntraId. More details about issues shown here:

enter image description here

In this screenshot, you can see the employee id field I'm trying to fetch using MS Graph client, but I'm getting null every time I try:

enter image description here

Here's my code used for fetching data via the graph client:

private static GraphServiceClient GetGraphClient(string clientId, string tenantId, string clientSecret)
{
    // Set up the client credential authentication provider
    var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
            .Build();

    var authProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);

    // Create and return the GraphServiceClient with the authentication provider
    return new GraphServiceClient(authProvider);
}

Here's the code get the employee:

var result = await graphClient.Users
                        .GetAsync((requestConfiguration) =>
                            {
                               requestConfiguration.QueryParameters.Filter = $"displayname eq '{User.Mail}'";
                               requestConfiguration.QueryParameters.Select = ["employeeId", "EmployeeID", "EMP_ID"];
                            });

I'm getting all other basic details from claims.

Please help me get the employee id as well.


Solution

  • Initially, Registered Single-Tenant Microsoft Entra ID Application , Added and Granted Application type User.Read.All API Permission:

    enter image description here

    I created one test user as testUser1 and configured employeeId and mail.

    In Portal, Ensure that Employee ID should not be null in Properties, and should exist like below:

    enter image description here

    Use below modified code, To get a employee_ID of particular User:

    using Microsoft.Graph;
    using Azure.Identity; // For ClientSecretCredential
    using System;
    using System.Threading.Tasks;
    
    public class GraphClientExample
    {
        private static GraphServiceClient GetGraphClient(string clientId, string tenantId, string clientSecret)
        {
            // Use ClientSecretCredential for authentication
            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    
            // Return the GraphServiceClient using ClientSecretCredential
            return new GraphServiceClient(clientSecretCredential);
        }
    
        public static async Task FetchEmployee(string clientId, string tenantId, string clientSecret, string userMail)
        {
            if (string.IsNullOrEmpty(userMail))
            {
                Console.WriteLine("User mail is null or empty.");
                return;
            }
    
            // Initialize Graph client
            var graphClient = GetGraphClient(clientId, tenantId, clientSecret);
    
            try
            {
                // Fetch the user details
                var result = await graphClient.Users
                    .GetAsync((requestConfiguration) =>
                    {
                        // Apply filter and select query
                        requestConfiguration.QueryParameters.Filter = $"mail eq '{userMail}'";
                        requestConfiguration.QueryParameters.Select = new[] { "id", "displayName", "mail", "employeeId" };
                    });
    
                // Check if any users are found
                if (result?.Value != null && result.Value.Count > 0)
                {
                    foreach (var user in result.Value)
                    {
                        Console.WriteLine($"User Found: {user.DisplayName}, ID:{user.Id}, Email: {user.Mail}, Employee ID: { user.EmployeeId}");
                    }
                }
                else
                {
                    Console.WriteLine("No matching user found.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    
        public static async Task Main(string[] args)
        {
            // Replace these with your app registration details
            string clientId = "<YOUR CLIENT ID";
            string tenantId = "YOUR TENANAT ID";
            string clientSecret = "YOUR CLIENT SECRET";
            string userMail = "<YOUR TEST USER EMAIL SEARCH>"; // Email to search
    
            await FetchEmployee(clientId, tenantId, clientSecret, userMail);
        }
    }
    
    

    Response:

    enter image description here