シナリオに基づいて 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 代理プロバイダー
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 ID ライブラリは、使用される認証プロバイダーを提供します。

  • .NET 開発者は 、Azure.Identity パッケージを追加する必要があります。
  • TypeScript および 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 AuthorizationCodeCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

// https://learn.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 クライアント資格情報フロー」をご覧ください。

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

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

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

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

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

var graphClient = new GraphServiceClient(clientCertCredential, scopes);

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

// The client credentials flow requires that you request the
// /.default scope, and pre-configure 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" };

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

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

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

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

On-behalf-of provider

代理フローは、アプリケーションが Microsoft Graph APIを呼び出すサービス/Web API を呼び出すときに適用されます。 詳細については、「Microsoft ID プラットフォームと OAuth2.0 On-Behalf-Of フロー」をご覧ください。

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 OnBehalfOfCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

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

var onBehalfOfCredential = new OnBehalfOfCredential(
    tenantId, clientId, clientSecret, oboToken, options);

var graphClient = new GraphServiceClient(onBehalfOfCredential, scopes);

暗黙的プロバイダー

暗黙的な認証フローは、その 欠点のため推奨されません。 ネイティブ アプリやシングルページ アプリなどのパブリック クライアントでは、代わりに 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 DeviceCodeCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
    ClientId = clientId,
    TenantId = tenantId,
    // Callback function that receives the user prompt
    // Prompt contains the generated device code that user must
    // enter during the auth process in the browser
    DeviceCodeCallback = (code, cancellation) =>
    {
        Console.WriteLine(code.Message);
        return Task.FromResult(0);
    },
};

// https://learn.microsoft.com/dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(options);

var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);

統合 Windows プロバイダー

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

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

アクセス トークン プロバイダー

public class IntegratedWindowsTokenProvider : IAccessTokenProvider
{
    private readonly IPublicClientApplication publicClient;

    /// <summary>
    /// Initializes a new instance of the <see cref="IntegratedWindowsTokenProvider"/> class.
    /// </summary>
    /// <param name="clientId">The client ID from the app registration in Azure.</param>
    /// <param name="tenantId">The tenant ID from the app registration in Azure.</param>
    public IntegratedWindowsTokenProvider(string clientId, string tenantId)
    {
        // From MSAL (Microsoft.Identity.Client)
        publicClient = PublicClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .Build();

        AllowedHostsValidator = new AllowedHostsValidator();
    }

    /// <summary>
    /// Gets an <see cref="AllowedHostsValidator"/> that validates if the
    /// target host of a request is allowed for authentication.
    /// </summary>
    public AllowedHostsValidator AllowedHostsValidator { get; }

    /// <inheritdoc/>
    public async Task<string> GetAuthorizationTokenAsync(
        Uri uri,
        Dictionary<string, object>? additionalAuthenticationContext = null,
        CancellationToken cancellationToken = default)
    {
        var scopes = new[] { "User.Read" };
        var result = await publicClient
            .AcquireTokenByIntegratedWindowsAuth(scopes)
            .ExecuteAsync(cancellationToken);
        return result.AccessToken;
    }
}

クライアントを作成する

// 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 authenticationProvider = new BaseBearerTokenAuthenticationProvider(
    new IntegratedWindowsTokenProvider(clientId, tenantId));

var graphClient = new GraphServiceClient(authenticationProvider);

return graphClient;

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

対話型フローは、モバイル アプリケーション (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://learn.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 UsernamePasswordCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

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

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

var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);

次の手順