Auswahl eines Microsoft Graph Authentifizierungsanbieters basieren auf einem Szenario

Authentifizierungsanbieter implementieren den Code, der zum Abrufen eines Tokens mithilfe der Microsoft Authentication Library (MSAL) erforderlich ist. Sie behandeln eine Reihe potenzieller Fehler in Fällen wie inkrementelle Zustimmung, abgelaufene Kennwörter und bedingten Zugriff und legen dann den Autorisierungsheader der HTTP-Anforderung fest. Die folgende Tabelle listet die Menge der Anbieter auf, die zu den Szenarien für verschiedene Anwendungstypen passen.

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 verwendeten Authentifizierungsanbieter werden von den folgenden Azure Identity-Bibliotheken bereitgestellt:

Autorisierungscodeanbieter

Der Autorisierungscodeablauf ermöglicht es nativen und Web-Apps, Token im Namen des Benutzers sicher zu erhalten. 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 „im Auftrag von“-Ablauf ist anwendbar, wenn Ihre Anwendung eine Dienst-/Web-API aufruft, die wiederum 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ätecodeablauf erlaubt das Anmelden an Geräte ü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-Ablauf bietet Windows-Computern die Möglichkeit, stillschweigend ein Zugriffstoken zu erhalten, wenn sie einer Domäne beitreten. Weitere Informationen finden Sie unter Integrierte Windows-Authentifizierung.

Das Azure.Identity Paket unterstützt derzeit keine integrierte Windows-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 Ablauf wird von mobilen (Xamarin und UWP) sowie Desktop-Anwendungen verwendet, um Microsoft Graph im Auftrag des 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 seinem Benutzernamen und Kennwort anzumelden. Verwenden Sie diesen Ablauf nur, wenn sie keinen anderen OAuth-Ablauf 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