Partager via


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

La bibliothèque de client Azure Identity pour JavaScript fournit de nombreuses TokenCredential classes qui implémentent des flux de jetons OAuth2. La bibliothèque de client JavaScript Microsoft Graph 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. Ouvrez graphHelper.js et ajoutez le code suivant.

    import 'isomorphic-fetch';
    import { ClientSecretCredential } from '@azure/identity';
    import { Client } from '@microsoft/microsoft-graph-client';
    // prettier-ignore
    import { TokenCredentialAuthenticationProvider } from
      '@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials/index.js';
    
    let _settings = undefined;
    let _clientSecretCredential = undefined;
    let _appClient = undefined;
    
    export function initializeGraphForAppOnlyAuth(settings) {
      // Ensure settings isn't null
      if (!settings) {
        throw new Error('Settings cannot be undefined');
      }
    
      _settings = settings;
    
      // Ensure settings isn't null
      if (!_settings) {
        throw new Error('Settings cannot be undefined');
      }
    
      if (!_clientSecretCredential) {
        _clientSecretCredential = new ClientSecretCredential(
          _settings.tenantId,
          _settings.clientId,
          _settings.clientSecret,
        );
      }
    
      if (!_appClient) {
        const authProvider = new TokenCredentialAuthenticationProvider(
          _clientSecretCredential,
          {
            scopes: ['https://graph.microsoft.com/.default'],
          },
        );
    
        _appClient = Client.initWithMiddleware({
          authProvider: authProvider,
        });
      }
    }
    
  2. Remplacez la fonction vide initializeGraph dans index.js par ce qui suit.

    function initializeGraph(settings) {
      initializeGraphForAppOnlyAuth(settings);
    }
    

Ce code déclare deux propriétés privées, un ClientSecretCredential objet et un Client objet . La InitializeGraphForAppOnlyAuth fonction crée un instance de ClientSecretCredential, puis utilise cette instance pour créer un instance de Client. 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 à graphHelper.js.

    export async function getAppOnlyTokenAsync() {
      // Ensure credential isn't undefined
      if (!_clientSecretCredential) {
        throw new Error('Graph has not been initialized for app-only auth');
      }
    
      // Request token with given scopes
      const response = await _clientSecretCredential.getToken([
        'https://graph.microsoft.com/.default',
      ]);
      return response.token;
    }
    
  2. Remplacez la fonction vide displayAccessTokenAsync dans index.js par ce qui suit.

    async function displayAccessTokenAsync() {
      try {
        const appOnlyToken = await getAppOnlyTokenAsync();
        console.log(`App-only token: ${appOnlyToken}`);
      } catch (err) {
        console.log(`Error getting app-only access token: ${err}`);
      }
    }
    
  3. Exécutez la commande suivante dans votre interface CLI à la racine de votre projet.

    node index.js
    
  4. Entrez 1 lorsque vous êtes invité à entrer une option. L’application affiche un jeton d’accès.

    JavaScript Graph App-Only Tutorial
    
    [1] Display access token
    [2] List users
    [3] Make a Graph call
    [0] Exit
    
    Select an option [1...3 / 0]: 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