この記事では、「Microsoft Graph とアプリ専用認証を使用して .NET アプリをビルドする」で作成したアプリケーションに アプリ専用認証を追加します。
.NET 用の Azure Identity クライアント ライブラリには、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。
Microsoft Graph .NET クライアント ライブラリでは、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。
アプリ専用認証用に Graph クライアントを構成する
このセクションでは、 ClientSecretCredential クラスを使用して、 クライアント資格情報フローを使用してアクセス トークンを要求します。
GraphHelper.cs という名前の GraphTutorial ディレクトリに新しいファイルを作成し、そのファイルに次のコードを追加します。
using Azure.Core; using Azure.Identity; using Microsoft.Graph; using Microsoft.Graph.Models; class GraphHelper { }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) { GraphHelper.settings = settings; // Ensure settings isn't null _ = settings ?? throw new NullReferenceException("Settings cannot be null"); GraphHelper.settings = settings; clientSecretCredential ??= new ClientSecretCredential( GraphHelper.settings.TenantId, GraphHelper.settings.ClientId, GraphHelper.settings.ClientSecret); appClient ??= new GraphServiceClient( clientSecretCredential, /* Use the default scope, which will request the scopes configured on the app registration */ ["https://graph.microsoft.com/.default"]); }Program.csの空の
InitializeGraph関数 を 次のように置き換えます。void InitializeGraph(Settings settings) { GraphHelper.InitializeGraphForAppOnlyAuth(settings); }
このコードでは、 ClientSecretCredential オブジェクトと GraphServiceClient オブジェクトの 2 つのプライベート プロパティを宣言します。
InitializeGraphForAppOnlyAuth関数は、ClientSecretCredentialの新しいインスタンスを作成し、そのインスタンスを使用してGraphServiceClientの新しいインスタンスを作成します。 API 呼び出しが _appClientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。
ClientSecretCredential をテストする
次に、 ClientSecretCredentialからアクセス トークンを取得するコードを追加します。
次の関数を
GraphHelperクラスに追加します。public static async Task<string> GetAppOnlyTokenAsync() { // Ensure credential isn't null _ = clientSecretCredential ?? throw new NullReferenceException("Graph has not been initialized for app-only auth"); // Request token with given scopes var context = new TokenRequestContext(["https://graph.microsoft.com/.default"]); var response = await clientSecretCredential.GetTokenAsync(context); return response.Token; }Program.csの空の
DisplayAccessTokenAsync関数 を 次のように置き換えます。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}"); } }アプリをビルドして実行します。 オプションの入力を求められたら、「
1」と入力します。 アプリケーションにアクセス トークンが表示されます。.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...ヒント
検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してアプリ専用アクセス トークンをデコードできます。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の
role要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。