Authentication in Azure App Console and query in the Microsoft Graph application

Carlos Jahir Carreño Hernandez 125 Reputation points
2023-10-11T21:14:18.1066667+00:00

Hello, thank you for all the advice you have been able to provide me in these groups following the guides and blogs. I'm having issues with authentication and queries. I tried to follow the exercise provided by Microsoft and reached this point.

  1. graphHelper.cs
using System.Diagnostics;
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
//-----------------------------------------------
//Aqui se configura todo el acceso de autenticacion a la aplicacion
[DebuggerDisplay($"{{{nameof(GetDebuggerDisplay)}(),nq}}")]
class GraphHelper
{
    // Esta configira el aceso que se encuentra ne el archivo .jason appsettings
    private static Settings? _settings;
    // Credenciales de autenticacion del usuario 
    private static DeviceCodeCredential? _deviceCodeCredential;
    // configuracion del cliente con el usuario de autenticacion
    private static GraphServiceClient? _userClient;

    public static void InitializeGraphForUserAuth(Settings settings,
    Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
    {
    _settings = settings;

        var options = new DeviceCodeCredentialOptions
         {
            ClientId = settings.ClientId,
            TenantId = settings.TenantId,
            DeviceCodeCallback = deviceCodePrompt,
        };

        _deviceCodeCredential = new DeviceCodeCredential(options);

        _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
    }

    public static async Task<string> GetUserTokenAsync()
    {
        // Ensure credential isn't null
        _ = _deviceCodeCredential ??
        throw new System.NullReferenceException("Graph has not been initialized for user auth");

        // Ensure scopes isn't null
        _ = _settings?.GraphUserScopes ?? throw new System.ArgumentNullException("Argument 'scopes' cannot be null");

        // Request token with given scopes
        var context = new TokenRequestContext(_settings.GraphUserScopes);
        var response = await _deviceCodeCredential.GetTokenAsync(context);
        return response.Token;
    }
    //----------------------------------------------------------------------
    public static Task<Device?> GetUserAsync()
    {
        // Ensure client isn't null
        _ = _userClient ??
            throw new System.NullReferenceException("Graph has not been initialized for user auth");

        return _userClient.Devices.GetAsync((config) =>
        {
            // Only request specific properties
            config.QueryParameters.Select = new[] {"displayName", "deviceId"};
        });
    }

    private string GetDebuggerDisplay()
    {
        return ToString();
    }
}

  1. program.cs
Console.WriteLine("Dispositivos\n");
var settings = Settings.LoadSettings();

//Inincializacion de MS graph
InitializeGraph(settings);

//Greet he user by name
await GreetUserAsync();

int choice = -1;

while (choice != 0)
{
    Console.WriteLine("Seleccione una de las siguiente sopciones");
    Console.WriteLine("0. Exit");
    Console.WriteLine("1. Display access token");

    try
    {
        choice = int.Parse(Console.ReadLine() ?? string.Empty);
    }
    catch (System.FormatException)
    {
        // Set to invalid value
        choice = -1;
    }

    switch(choice)
    {
        case 0:
            // Exit the program
            Console.WriteLine("Adios...");
            break;
        case 1:
            // Display access token
            await DisplayAccessTokenAsync();
            break;
        default:
            Console.WriteLine("Opcion no valida");
            break;
    }
}
    void InitializeGraph(Settings settings)
{
    GraphHelper.InitializeGraphForUserAuth(settings,
        (info, cancel) =>
        {
            // Display the device code message to
            // the user. This tells them
            // where to go to sign in and provides the
            // code to use.
            Console.WriteLine(info.Message);
            return Task.FromResult(0);
        });
}
{
    // TODO
}

async Task GreetUserAsync()
{
    try
    {
        var devicePerson = await GraphHelper.GetUserAsync();
        Console.WriteLine($"Nombre Dispositivo, {device?.DisplayName}!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error getting devicePerson: {ex.Message}");
    }
}

async Task DisplayAccessTokenAsync()
{
    try
    {
        var userToken = await GraphHelper.GetUserTokenAsync();
        Console.WriteLine($"User token: {userToken}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error getting user access token: {ex.Message}");
    }
}

I have followed this exercise and other tutorials: https://learn.microsoft.com/en-us/graph/tutorials/dotnet?tutorial-step=2&tabs=aad. Thanks

Microsoft Security Microsoft Graph
Developer technologies C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.