Auswählen eines Microsoft Graph-Authentifizierungsanbieters basierend auf dem Szenario

Authentifizierungsanbieter implementieren den Code, der zum Abrufen eines Tokens mithilfe der Microsoft Authentication Library (MSAL) erforderlich ist, behandeln einige potenzielle Fehler für Fälle wie inkrementelle Zustimmung, abgelaufene Kennwörter und bedingten Zugriff und legen dann den HTTP-Anforderungsautorisierungsheader fest. In der folgenden Tabelle sind die Anbieter aufgeführt, die den Szenarien für verschiedene Anwendungstypen entsprechen.

Szenario Fluss/Zuweisung Zielgruppe Anbieter
Einzelseiten-App Autorisierungscode mit PKCE Delegierter Verbraucher/Organisation Autorisierungscodeanbieter
Web-App, welche Web-APIs aufruft
Autorisierungscode Delegierter Verbraucher/Organisation Autorisierungscodeanbieter
Client-Anmeldeinformationen Nur App Anbieter von Clientanmeldeinformationen
Web-API, welches Web-APIs aufruft
Im Auftrag von Delegierter Verbraucher/Organisation Anbieter im Auftrag von
Client-Anmeldeinformationen Nur App Anbieter von Clientanmeldeinformationen
Desktop-App, welche Web-APIs aufruft
Interaktiv Delegierter Verbraucher/Organisation Interaktiver Anbieter
Integriertes Windows Delegierte Organisation Integrierter Windows-Anbieter
Ressourcenbesitzer Delegierte Organisation Benutzername/Kennwortanbieter
Gerätecode Delegierte Organisation Gerätecodeanbieter
Daemon-App
Client-Anmeldeinformationen Nur App Anbieter von Clientanmeldeinformationen
Mobile App, welche Web-APIs aufruft
Interaktiv Delegierter Verbraucher/Organisation Interaktiver Anbieter

Hinweis

Die folgenden Codeausschnitte wurden mit den neuesten Versionen ihrer jeweiligen SDKs geschrieben. Wenn bei diesen Codeausschnitten Compilerfehler auftreten, stellen Sie sicher, dass Sie über die neuesten Versionen verfügen. Die folgenden Azure Identity-Bibliotheken stellen die verwendeten Authentifizierungsanbieter bereit:

Autorisierungscodeanbieter

Der Autorisierungscodeflow ermöglicht es nativen Apps und Web-Apps, Token im Namen des Benutzers sicher abzurufen. Weitere Informationen finden Sie unter Microsoft Identity Plattform und OAuth 2.0 Autorisierungscodeablauf.

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

Der Ablauf für Client-Anmeldeinformationen ermöglicht die Ausführung von Dienstanwendungen ohne Benutzerinteraktion. Der Zugriff basiert auf der Identität der Anwendung. Weitere Informationen finden Sie unter Microsoft Identity Plattform und OAuth 2.0 Client-Anmeldeinformationsablauf.

Mithilfe eines Clientzertifikats

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

Verwenden eines geheimen Clientschlüssels

// 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);

„Im Auftrag von“-Anbieter

Der On-Behalf-of-Flow ist anwendbar, wenn Ihre Anwendung eine Dienst-/Web-API aufruft, die die Microsoft Graph-API aufruft. Weitere Informationen finden Sie unter Microsoft Identity Plattform und OAuth 2.0 „im Auftrag von“-Ablauf.

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

Impliziter Anbieter

Der Flow für die implizite Authentifizierung wird aufgrund seiner Nachteile nicht empfohlen. Öffentliche Clients wie native Apps und Single-Page-Apps sollten jetzt stattdessen den Autorisierungscodeflow mit der PKCE-Erweiterung verwenden. Referenz.

Gerätecodeanbieter

Der Gerätecodeflow ermöglicht die Anmeldung bei Geräten über ein anderes Gerät. Weitere Informationen finden Sie unter Microsoft Identity Plattform und OAuth 2.0 Gerätecodeablauf.

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

Integrierter Windows-Anbieter

Der integrierte Windows-Flow ermöglicht es Windows-Computern, ein Zugriffstoken abzurufen, wenn sie im Hintergrund in die Domäne eingebunden sind. Weitere Informationen finden Sie unter Integrierte Windows-Authentifizierung.

Das Azure.Identity Paket unterstützt derzeit keine in Windows integrierte Authentifizierung. Erstellen Sie stattdessen mithilfe von MSAL einen benutzerdefinierten Zugriffstokenanbieter.

Zugriffstokenanbieter

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

Erstellen des Clients

// 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;

Interaktiver Anbieter

Der interaktive Flow wird von mobilen Anwendungen (Xamarin und UWP) und Desktopanwendungen verwendet, um Microsoft Graph im Namen eines Benutzers aufzurufen. Weitere Informationen finden Sie unter Token interaktiv erfassen.

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

Benutzername/Kennwort-Anbieter

Der Benutzername/Kennwort-Anbieter ermöglicht es einer Anwendung, einen Benutzer mit dessen Benutzername und Kennwort anzumelden. Verwenden Sie diesen Flow nur, wenn Sie keine anderen OAuth-Flows verwenden können. Weitere Informationen finden Sie unter Microsoft Identity Plattform und OAuth 2.0 Ressourcenbesitzer Kennwort-Anmeldeinformationen.

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

Nächste Schritte