skip to Main Content

I am trying to write a C# console app to get my own user attributes (such as businessPhones, displayName, givenName, id, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage, surname, and userPrincipalName) from Azure AD by using an interactive login? Using the standard login Windows that pops up when authenticating to AAD.

I started by doing this but ‘Microsoft.IdentityModel.Clients.ActiveDirectory’ is deprecated.

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Graph;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string clientId = "my client ID from app reg";
        string authority = "https://login.microsoftonline.com/your-tenant-id";
        string resource = "https://graph.microsoft.com";

2

Answers


  1. Chosen as BEST ANSWER

    I tried to amend your code to use an interactive login instead of a Client Secret. But I get the following error. 'MeRequestBuilder' does not contain a definition for 'Request' and no accessible extension method 'Request' accepting a first argument of type 'MeRequestBuilder' could be found (are you missing a using directive or an assembly reference?)

    using System;
    using System.Threading.Tasks;
    using Microsoft.Graph;
    using Azure.Identity;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            var scopes = new[] { "User.Read" };
            var tenantId = "9fa4d4d6-7541-490f-a49a-111d3392731f";
            var clientId = "45eca948-6cdd-4b98-ad9b-7aa6b36038c4";
    
            // Create an interactive credential
            var interactiveCredential = new InteractiveBrowserCredential();
    
            // Authenticate with Microsoft Graph
            var graphClient = new GraphServiceClient(interactiveCredential, scopes);
    
            try
            {
                // Fetch user details using GET request to Microsoft Graph API
                var result = await graphClient.Me.Request().GetAsync();
    
                // Output user details
                Console.WriteLine($"User ID: {result.Id}");
                Console.WriteLine($"Display Name: {result.DisplayName}");
                Console.WriteLine($"Email: {result.Mail}");
                Console.WriteLine($"Job Title: {result.JobTitle}");
                // Add more properties as needed
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user details: {ex.Message}");
            }
        }
    }
    

  2. Create an Azure AD application and grant User.Read API permission:

    enter image description here

    Generate the auth-code by using below endpoint and sign-in with the user account:

    https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
    &client_id=ClientID
    &response_type=code
    &redirect_uri=https://replyUrlNotSet
    &response_mode=query
    &scope=https://graph.microsoft.com/.default
    &state=12345
    

    enter image description here

    You can make use of below code to get the singed in user details:

    using Microsoft.Graph;
    using Azure.Identity;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            
            var scopes = new[] { "User.Read" };
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            var authorizationCode = "authcodefromabove";
    
            var options = new AuthorizationCodeCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
            };
    
            var authCodeCredential = new AuthorizationCodeCredential(
                tenantId, clientId, clientSecret, authorizationCode, options);
    
            var graphClient = new GraphServiceClient(authCodeCredential, scopes);
    
            try
            {
                // Fetch user details using GET request to Microsoft Graph API
                var result = await graphClient.Me.GetAsync();
    
                // Output user details
                Console.WriteLine($"User ID: {result.Id}");
                Console.WriteLine($"Display Name: {result.DisplayName}");
                Console.WriteLine($"Email: {result.Mail}");
                Console.WriteLine($"Job Title: {result.JobTitle}");
                // Add more properties as needed
    
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user details: {ex.Message}");
            }
        }
    }
    

    enter image description here

    Modify the code and use the below to get the details you require:

        try
            {
                var result = await graphClient.Me
                    .GetAsync((requestConfiguration) =>
                    {
                        requestConfiguration.QueryParameters.Select = new string[] { "displayName", "id", "officeLocation", "givenName", "businessPhones", "jobTitle", "mobilePhone", "preferredLanguage", "surname", "userPrincipalName", "mail" };
                    });
    
                // Output user details
                Console.WriteLine($"User ID: {result.Id}");
                Console.WriteLine($"Display Name: {result.DisplayName}");
                Console.WriteLine($"Email: {result.Mail}");
                Console.WriteLine($"Job Title: {result.JobTitle}");
                Console.WriteLine($"Business Phones: {string.Join(",", result.BusinessPhones)}");
                Console.WriteLine($"Given Name: {result.GivenName}");
                Console.WriteLine($"Mobile Phone: {result.MobilePhone}");
                Console.WriteLine($"Office Location: {result.OfficeLocation}");
                Console.WriteLine($"Preferred Language: {result.PreferredLanguage}");
                Console.WriteLine($"Surname: {result.Surname}");
                Console.WriteLine($"User Principal Name: {result.UserPrincipalName}");
                // Add more properties as needed
    
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user details: {ex.Message}");
            }
        }
    }
    

    And get response like below:

    enter image description here

    UPDATED: To make use of Interactive browser credential flow make use of below code:

    using Microsoft.Graph;
    using Azure.Identity;
    
    class Program
    {
        static async Task Main(string[] args)
        {
    
            var scopes = new[] { "User.Read" };
    
    
    var tenantId = "TenantID";
    var clientId = "ClientID";
    var options = new InteractiveBrowserCredentialOptions
    {
        TenantId = tenantId,
        ClientId = clientId,
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
        // MUST be http://localhost or http://localhost:PORT
        // See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
        RedirectUri = new Uri("http://localhost"),
    };
    
    // https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
    var interactiveCredential = new InteractiveBrowserCredential(options);
    
    var graphClient = new GraphServiceClient(interactiveCredential, scopes);
    
            try
            {
                // Fetch user details using GET request to Microsoft Graph API
                var result = await graphClient.Me.GetAsync();
    
                // Output user details
                Console.WriteLine($"User ID: {result.Id}");
                Console.WriteLine($"Display Name: {result.DisplayName}");
                Console.WriteLine($"Email: {result.Mail}");
                Console.WriteLine($"Job Title: {result.JobTitle}");
                // Add more properties as needed
    
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error fetching user details: {ex.Message}");
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search