Azure Active Directory-Bibliotheken für .NET

Übersicht

Melden Sie sich mit Azure Active Directory (Azure AD) an, und greifen Sie auf geschützte Web-APIs zu.

Informationen zu den ersten Schritten bei der Entwicklung von Anwendungen mit Azure Active Directory finden Sie im Microsoft Identity Platform.

Clientbibliothek

Stellen Sie mithilfe von OpenID Connect und OAuth 2.0 mit der Microsoft Authentication Library for .NET (MSAL.NET) den bereichsbezogenen Zugriff auf web-APIs bereit, die von Azure AD geschützt sind.

Installieren Sie das NuGet-Paket direkt über die Paket-Manager-Konsole in Visual Studio oder mit der .NET Core CLI.

Visual Studio-Paket-Manager

Install-Package Microsoft.Identity.Client

.NET Core-CLI

dotnet add package Microsoft.Identity.Client

Codebeispiel

Abrufen eines Zugriffstokens für die Microsoft-Graph-API in einer Desktopanwendung (öffentlicher Client).

/* Include this using directive:
using Microsoft.Identity.Client;
*/

string ClientId = "11111111-1111-1111-1111-111111111111"; // Application (client) ID
string Tenant = "common";
string Instance = "https://login.microsoftonline.com/";

string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";
string[] scopes = new string[] { "user.read" };

AuthenticationResult authResult = null;

var app = PublicClientApplicationBuilder.Create(ClientId)
                .WithAuthority($"{Instance}{Tenant}")
                .WithRedirectUri("http://localhost")
                .Build();

var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();

try
{
    // Always first try to acquire a token silently.
    authResult = await app.AcquireTokenSilent(scopes, firstAccount)
        .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
    // If an MsalUiRequiredException occurred when AcquireTokenSilent was called,
    // it indicates you need to call AcquireTokenInteractive to acquire a token.
    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

    try
    {
        authResult = await app.AcquireTokenInteractive(scopes)
            .WithAccount(firstAccount)
            .WithPrompt(Prompt.SelectAccount)
            .ExecuteAsync();
    }
    catch (MsalException msalex)
    {
        System.Diagnostics.Debug.WriteLine($"Error acquiring Token:{System.Environment.NewLine}{msalex}");
    }
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine($"Error acquiring token silently:{System.Environment.NewLine}{ex}");
    return;
}

if (authResult != null)
{
    System.Diagnostics.Debug.WriteLine($"Access token:{System.Environment.NewLine}{authResult.AccessToken}");
}

Beispiele

Erkunden Sie die vollständige Sammlung von Microsoft Identity Platform Codebeispielen.