Partager via


Ajouter l’authentification d’application uniquement aux applications Java 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 Java avec Microsoft Graph et l’authentification d’application uniquement.

La bibliothèque de client Azure Identity pour Java fournit de nombreuses TokenCredential classes qui implémentent des flux de jetonS OAuth2. Le Kit de développement logiciel (SDK) Microsoft Graph pour Java 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 ./app/src/main/java/graphapponlytutorial nommé Graph.java et ajoutez le code suivant à ce fichier.

    package graphapponlytutorial;
    
    import java.util.Properties;
    
    import com.azure.core.credential.AccessToken;
    import com.azure.core.credential.TokenRequestContext;
    import com.azure.identity.ClientSecretCredential;
    import com.azure.identity.ClientSecretCredentialBuilder;
    import com.microsoft.graph.models.UserCollectionResponse;
    import com.microsoft.graph.serviceclient.GraphServiceClient;
    
  2. Ajoutez une définition de classe Graph vide.

    public class Graph {
    }
    
  3. Ajoutez ce code à la classe Graph.

    private static Properties _properties;
    private static ClientSecretCredential _clientSecretCredential;
    private static GraphServiceClient _appClient;
    
    public static void initializeGraphForAppOnlyAuth(Properties properties) throws Exception {
        // Ensure properties isn't null
        if (properties == null) {
            throw new Exception("Properties cannot be null");
        }
    
        _properties = properties;
    
        if (_clientSecretCredential == null) {
            final String clientId = _properties.getProperty("app.clientId");
            final String tenantId = _properties.getProperty("app.tenantId");
            final String clientSecret = _properties.getProperty("app.clientSecret");
    
            _clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId(clientId)
                .tenantId(tenantId)
                .clientSecret(clientSecret)
                .build();
        }
    
        if (_appClient == null) {
            _appClient = new GraphServiceClient(_clientSecretCredential,
                    new String[] { "https://graph.microsoft.com/.default" });
        }
    }
    
  4. Remplacez la fonction vide initializeGraph dans App.java par ce qui suit.

    private static void initializeGraph(Properties properties) {
        try {
            Graph.initializeGraphForAppOnlyAuth(properties);
        } catch (Exception e)
        {
            System.out.println("Error initializing Graph for user auth");
            System.out.println(e.getMessage());
        }
    }
    

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 Graph.

    public static String getAppOnlyToken() throws Exception {
        // Ensure credential isn't null
        if (_clientSecretCredential == null) {
            throw new Exception("Graph has not been initialized for app-only auth");
        }
    
        // Request the .default scope as required by app-only auth
        final String[] graphScopes = new String[] {"https://graph.microsoft.com/.default"};
    
        final TokenRequestContext context = new TokenRequestContext();
        context.addScopes(graphScopes);
    
        final AccessToken token = _clientSecretCredential.getToken(context).block();
        return token.getToken();
    }
    
  2. Remplacez la fonction vide displayAccessToken dans App.java par ce qui suit.

    private static void displayAccessToken() {
        try {
            final String accessToken = Graph.getAppOnlyToken();
            System.out.println("Access token: " + accessToken);
        } catch (Exception e) {
            System.out.println("Error getting access token");
            System.out.println(e.getMessage());
        }
    }
    
  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.

    Java App-Only 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 utilisateur (pour les comptes professionnels ou scolaires 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 scp jeton contient les étendues d’autorisation Microsoft Graph attendues.

Étape suivante