シナリオに基づいて Microsoft Graph 認証プロバイダーを選択する

認証プロバイダーは、Microsoft 認証ライブラリ (MSAL) を使用してトークンを取得するために必要なコードを実装し、増分同意、期限切れのパスワード、条件付きアクセスなどの場合の潜在的なエラーの数を処理します。 次に、HTTP リクエスト認証ヘッダーを設定します。 次の表に、さまざまなアプリケーション タイプのシナリオに一致するプロバイダーのセットを示します。

シナリオ Flow/Grant 対象ユーザー プロバイダー
シングル ページ アプリ PKCE を使用した承認コード Delegated Consumer/Org 承認コード プロバイダー
Web API を呼び出す Web アプリ
認証コード Delegated Consumer/Org 承認コード プロバイダー
Client Credentials App Only クライアント資格情報プロバイダー
Web API を呼び出す Web API
On Behalf Of Delegated Consumer/Org On-Behalf-of provider
Client Credentials App Only クライアント資格情報プロバイダー
Web API を呼び出す デスクトップ アプリ
対話操作が可能 Delegated Consumer/Org 対話型プロバイダー
統合 Windows Delegated Org 統合 Windows プロバイダー
リソースの所有者 Delegated Org ユーザー名/パスワード プロバイダー
Device Code Delegated Org デバイス コード プロバイダー
Daemon アプリ
Client Credentials App Only クライアント資格情報プロバイダー
Web API を呼び出すモバイル アプリ
対話操作が可能 Delegated Consumer/Org 対話型プロバイダー

注意

次のコード スニペットは、それぞれの SDK の最新バージョンで記述されています。 これらのスニペットでコンパイラ エラーが発生した場合は、最新バージョンを使用していることを確認してください。 使用される認証プロバイダーは、次の Azure Identity ライブラリによって提供されます。

  • .NET 開発者は 、Azure.Identity パッケージを追加する必要があります。
  • JavaScript 開発者は、 @azure/ID ライブラリを追加する必要があります。
  • Java と Android の開発者は、 azure-IDENTITY ライブラリを追加する必要があります。

認証コード プロバイダー

認証コード フローにより、ネイティブ アプリとWeb アプリはユーザーの名前でトークンを安全に取得できます。 詳細については、「Microsoft ID プラットフォームと OAuth 2.0 認証コード フロー」を参照してください。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// For authorization code flow, the user signs into the Microsoft
// identity platform, and the browser is redirected back to your app
// with an authorization code in the query parameters
var authorizationCode = "AUTH_CODE_FROM_REDIRECT";

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// https://docs.microsoft.com/dotnet/api/azure.identity.authorizationcodecredential
var authCodeCredential = new AuthorizationCodeCredential(
    tenantId, clientId, clientSecret, authorizationCode, options);

var graphClient = new GraphServiceClient(authCodeCredential, scopes);

Client Credentials Provider

クライアント資格情報フローにより、ユーザーの操作なしでサービス アプリケーションを実行できます。 アクセスは、アプリケーションの ID 基づいています。 詳細については、「Microsoft ID プラットフォームと OAuth 2.0 クライアント資格情報フロー」をご覧ください。

クライアント シークレットの使用

// The client credentials flow requires that you request the
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// https://docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

クライアント証明書の使用

var scopes = new[] { "https://graph.microsoft.com/.default" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientCertificate = new X509Certificate2("MyCertificate.pfx");

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// https://docs.microsoft.com/dotnet/api/azure.identity.clientcertificatecredential
var clientCertCredential = new ClientCertificateCredential(
    tenantId, clientId, clientCertificate, options);

var graphClient = new GraphServiceClient(clientCertCredential, scopes);

On-behalf-of provider

on-behalf-of フローは、アプリケーションが service/web APIを呼び出し、次に Microsoft Graph API を呼び出す場合に適用されます。 詳細については、「Microsoft ID プラットフォームと OAuth2.0 On-Behalf-Of フロー」をご覧ください。

このパッケージでは Azure.Identity 、バージョン 1.4.0 以降の代理フローはサポートされていません。 代わりに、MSAL を使用してカスタム認証プロバイダーを作成します。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// This is the incoming token to exchange using on-behalf-of flow
var oboToken = "JWT_TOKEN_TO_EXCHANGE";

var cca = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .Build();

// DelegateAuthenticationProvider is a simple auth provider implementation
// that allows you to define an async function to retrieve a token
// Alternatively, you can create a class that implements IAuthenticationProvider
// for more complex scenarios
var authProvider = new DelegateAuthenticationProvider(async (request) => {
    // Use Microsoft.Identity.Client to retrieve token
    var assertion = new UserAssertion(oboToken);
    var result = await cca.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();

    request.Headers.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});

var graphClient = new GraphServiceClient(authProvider);

暗黙的プロバイダー

暗黙的な認証フローは、その 欠点のためにお勧めしません。 ネイティブ アプリや JavaScript アプリなどのパブリック クライアントでは、代わりに PKCE 拡張機能で承認コード フローを使用する必要があります。 リファレンス

Device Code Provider

デバイス コード フローにより、別のデバイスを介してデバイスにサインインできます。 詳細については、「Microsoft ID プラットフォームと OAuth 2.0 デバイス コード フロー」を参照してください。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Callback function that receives the user prompt
// Prompt contains the generated device code that use must
// enter during the auth process in the browser
Func<DeviceCodeInfo, CancellationToken, Task> callback = (code, cancellation) => {
    Console.WriteLine(code.Message);
    return Task.FromResult(0);
};

// https://docs.microsoft.com/dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(
    callback, tenantId, clientId, options);

var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);

統合 Windows プロバイダー

統合 Windows フローは、Windows コンピューターがドメインに参加しているときに、アクセストークンをサイレントに取得する方法を提供します。 詳細については、「統合 Windows 認証」を参照してください。

パッケージは Azure.Identity 現在、Windows 統合認証をサポートしていません。 代わりに、MSAL を使用してカスタム認証プロバイダーを作成します。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

var pca = PublicClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .Build();

// DelegateAuthenticationProvider is a simple auth provider implementation
// that allows you to define an async function to retrieve a token
// Alternatively, you can create a class that implements IAuthenticationProvider
// for more complex scenarios
var authProvider = new DelegateAuthenticationProvider(async (request) => {
    // Use Microsoft.Identity.Client to retrieve token
    var result = await pca.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();

    request.Headers.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});

var graphClient = new GraphServiceClient(authProvider);

インタラクティブ プロバイダー

インタラクティブ フローは、モバイル アプリケーション (Xamarin およびUWP) およびデスクトップ アプリケーションで、ユーザーの名前で Microsoft Graph を呼び出すために使用されます。 詳細については、「トークンをインタラクティブに取得する」を参照してください。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

// using Azure.Identity;
var options = new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
    // MUST be http://localhost or http://localhost:PORT
    // See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
    RedirectUri = new Uri("http://localhost"),
};

// https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
var interactiveCredential = new InteractiveBrowserCredential(options);

var graphClient = new GraphServiceClient(interactiveCredential, scopes);

ユーザー名/パスワード プロバイダー

ユーザー名/パスワード プロバイダーを使用すると、アプリケーションはユーザー名とパスワードを使用してユーザーにサインインできます。 このフローは、他の OAuth ローを使用できない場合にのみ使用してください。 詳細については、「Microsoft ID プラットフォームと OAuth 2.0 リソース所有者のパスワード資格情報」をご覧ください。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

// using Azure.Identity;
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

var userName = "adelev@contoso.com";
var password = "P@ssword1!";

// https://docs.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential
var userNamePasswordCredential = new UsernamePasswordCredential(
    userName, password, tenantId, clientId, options);

var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);

次の手順