Partager via


Ajouter l’authentification d’application uniquement aux applications .NET pour Microsoft Graph

Dans cet article, vous allez ajouter l’authentification d’application uniquement à l’application que vous avez créée dans Générer des applications .NET avec Microsoft Graph et l’authentification d’application uniquement.

La bibliothèque de client Azure Identity pour .NET fournit de nombreuses TokenCredential classes qui implémentent des flux de jetonS OAuth2. La bibliothèque de client Microsoft Graph .NET utilise ces classes pour authentifier les appels à Microsoft Graph.

Configurer le client Graph pour l’authentification d’application uniquement

Dans cette section, vous utilisez la ClientSecretCredential classe pour demander un jeton d’accès à l’aide du flux d’informations d’identification du client.

  1. Créez un fichier dans le répertoire GraphTutorial nommé GraphHelper.cs et ajoutez le code suivant à ce fichier.

    using Azure.Core;
    using Azure.Identity;
    using Microsoft.Graph;
    using Microsoft.Graph.Models;
    
    class GraphHelper
    {
    }
    
  2. Ajoutez ce code à la classe GraphHelper.

    // Settings object
    private static Settings? _settings;
    // App-ony auth token credential
    private static ClientSecretCredential? _clientSecretCredential;
    // Client configured with app-only authentication
    private static GraphServiceClient? _appClient;
    
    public static void InitializeGraphForAppOnlyAuth(Settings settings)
    {
        _settings = settings;
    
        // Ensure settings isn't null
        _ = settings ??
            throw new System.NullReferenceException("Settings cannot be null");
    
        _settings = settings;
    
        if (_clientSecretCredential == null)
        {
            _clientSecretCredential = new ClientSecretCredential(
                _settings.TenantId, _settings.ClientId, _settings.ClientSecret);
        }
    
        if (_appClient == null)
        {
            _appClient = new GraphServiceClient(_clientSecretCredential,
                // Use the default scope, which will request the scopes
                // configured on the app registration
                new[] {"https://graph.microsoft.com/.default"});
        }
    }
    
  3. Remplacez la fonction vide InitializeGraph dans Program.cs par ce qui suit.

    void InitializeGraph(Settings settings)
    {
        GraphHelper.InitializeGraphForAppOnlyAuth(settings);
    }
    

Ce code déclare deux propriétés privées, un ClientSecretCredential objet et un GraphServiceClient objet . La InitializeGraphForAppOnlyAuth fonction crée un instance de ClientSecretCredential, puis utilise cette instance pour créer un instance de GraphServiceClient. Chaque fois qu’un appel d’API est effectué à Microsoft Graph via , _appClientil utilise les informations d’identification fournies pour obtenir un jeton d’accès.

Tester clientSecretCredential

Ensuite, ajoutez du code pour obtenir un jeton d’accès à partir de .ClientSecretCredential

  1. Ajoutez la fonction suivante à la classe GraphHelper.

    public static async Task<string> GetAppOnlyTokenAsync()
    {
        // Ensure credential isn't null
        _ = _clientSecretCredential ??
            throw new System.NullReferenceException("Graph has not been initialized for app-only auth");
    
        // Request token with given scopes
        var context = new TokenRequestContext(new[] {"https://graph.microsoft.com/.default"});
        var response = await _clientSecretCredential.GetTokenAsync(context);
        return response.Token;
    }
    
  2. Remplacez la fonction vide DisplayAccessTokenAsync dans Program.cs par ce qui suit.

    async Task DisplayAccessTokenAsync()
    {
        try
        {
            var appOnlyToken = await GraphHelper.GetAppOnlyTokenAsync();
            Console.WriteLine($"App-only token: {appOnlyToken}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting app-only access token: {ex.Message}");
        }
    }
    
  3. Générez et exécutez l’application. Entrez 1 lorsque vous êtes invité à entrer une option. L’application affiche un jeton d’accès.

    .NET Graph Tutorial
    
    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List users
    3. Make a Graph call
    1
    App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...
    

    Conseil

    À des fins de validation et de débogage uniquement, vous pouvez décoder les jetons d’accès d’application uniquement à l’aide de l’analyseur de jetons en ligne de Microsoft à l’adresse https://jwt.ms. L’analyse de votre jeton peut être utile si vous rencontrez des erreurs de jeton lors de l’appel de Microsoft Graph. Par exemple, vérifier que la revendication dans le role jeton contient les étendues d’autorisation Microsoft Graph attendues.

Étape suivante