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

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

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

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

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

  1. ./app/src/メイン/java/graphapponlytutorial ディレクトリにGraph.java という名前の新しいファイルを作成し、そのファイルに次のコードを追加します。

    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. 空の Graph クラス定義を追加します。

    public class Graph {
    }
    
  3. 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. App.javaの空の initializeGraph 関数 次のように置き換えます。

    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());
        }
    }
    

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

ClientSecretCredential をテストする

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

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

    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. アプリをビルドして実行します。 オプションの入力を求められたら、「 1 」と入力します。 アプリケーションにアクセス トークンが表示されます。

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

    ヒント

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

次の手順