Notes
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Vue d’ensemble
Connectez des utilisateurs et accédez aux API web protégées avec Azure Active Directory (Azure AD).
Pour commencer à développer des applications avec Azure Active Directory, consultez les Plateforme d'identités Microsoft.
Bibliothèque cliente
Fournissez un accès délimité aux API web protégées par Azure AD à l’aide d’OpenID Connect et d’OAuth 2.0 avec la bibliothèque d’authentification Microsoft pour .NET (MSAL.NET).
Installez le package NuGet directement à partir de la Console du Gestionnaire de package Visual Studio ou avec la CLI .NET Core.
Gestionnaire de package Visual Studio
Install-Package Microsoft.Identity.Client
CLI .NET Core
dotnet add package Microsoft.Identity.Client
Exemple de code
Récupérez un jeton d’accès pour microsoft API Graph dans une application de bureau (client public).
/* 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}");
}
Exemples
- application web ASP.NET Core - connecter les utilisateurs
- Application de bureau Windows (WPF) - connecter les utilisateurs
- Utiliser un contrôle d’accès basé sur les rôles (RBAC) dans une application
Explorez la collection complète d’exemples de code Plateforme d'identités Microsoft.
Azure SDK for .NET