Microsoft Graph 用 JavaScript アプリにアプリ専用認証を追加する

この記事では、「Microsoft Graph とアプリ専用認証を使用して JavaScript アプリをビルドする」で作成したアプリケーションに アプリ専用認証を追加します。

JavaScript 用の Azure Identity クライアント ライブラリには、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。 Microsoft Graph JavaScript クライアント ライブラリでは、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。

アプリ専用認証用に Graph クライアントを構成する

このセクションでは、 ClientSecretCredential クラスを使用して、 クライアント資格情報フローを使用してアクセス トークンを要求します。

  1. graphHelper.js を開き、次のコードを追加します。

    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. index.jsの空の initializeGraph 関数 次のように置き換えます。

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

このコードでは、 ClientSecretCredential オブジェクトと Client オブジェクトの 2 つのプライベート プロパティを宣言します。 InitializeGraphForAppOnlyAuth関数は、ClientSecretCredentialの新しいインスタンスを作成し、そのインスタンスを使用してClientの新しいインスタンスを作成します。 API 呼び出しが _appClientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。

ClientSecretCredential をテストする

次に、 ClientSecretCredentialからアクセス トークンを取得するコードを追加します。

  1. 次の関数を 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. index.jsの空の displayAccessTokenAsync 関数 次のように置き換えます。

    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. プロジェクトのルートで CLI で次のコマンドを実行します。

    node index.js
    
  4. オプションの入力を求められたら、「 1 」と入力します。 アプリケーションにアクセス トークンが表示されます。

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

    ヒント

    検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してアプリ専用アクセス トークンをデコードできます。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の role 要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。

次の手順