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 | Im Auftrag des Anbieters | |
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:
- .NET-Entwickler müssen das Azure.Identity-Paket hinzufügen.
- JavaScript-Entwickler müssen die @azure/Identitätsbibliothek hinzufügen.
- Java- und Android-Entwickler müssen die Azure-Identity-Bibliothek hinzufügen.
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 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-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.
Verwenden eines geheimen Clientschlüssels
// 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);
Mithilfe eines Clientzertifikats
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);
„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.
Das Azure.Identity
Paket unterstützt den On-Behalf-of-Fluss ab Version 1.4.0 nicht. Erstellen Sie stattdessen einen benutzerdefinierten Authentifizierungsanbieter mithilfe von 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);
Impliziter Anbieter
Der implizite Authentifizierungsfluss wird aufgrund seiner Nachteile nicht empfohlen. Öffentliche Clients wie native Apps und JavaScript-Apps sollten jetzt stattdessen den Autorisierungscodefluss 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 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);
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 einen benutzerdefinierten Authentifizierungsanbieter mithilfe von 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);
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://docs.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 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);
Nächste Schritte
- Codebeispiele, die Ihnen zeigen, wie Sie die Microsoft Identity Platform zum Sichern verschiedener Anwendungstypen verwenden, finden Sie unter Microsoft Identity Platform Codebeispiele (v2.0-Endpunkt).
- Der Authentifizierungsanbieter verlangt eine Client-ID. Sie müssen Ihre Anwendung registrieren, nachdem Sie Ihren Authentifizierungsanbieter eingerichtet haben.
- Lassen Sie uns wissen, ob ein erforderlicher OAuth-Ablauf derzeit nicht unterstützt wird, indem Sie für eine Microsoft Graph Funktionsanforderung stimmen oder diese öffnen.
Feedback
Feedback senden und anzeigen für