Azure Active Directory libraries for .NET
Overview
Sign in users and access protected web APIs with Azure Active Directory (Azure AD).
To get started developing applications with Azure Active Directory, see the Microsoft identity platform.
Client library
Provide scoped access to web APIs protected by Azure AD using OpenID Connect and OAuth 2.0 with the Microsoft Authentication Library for .NET (MSAL.NET).
Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.
Visual Studio Package Manager
Install-Package Microsoft.Identity.Client
.NET Core CLI
dotnet add package Microsoft.Identity.Client
Code example
Retrieve an access token for the Microsoft Graph API in a desktop application (public 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}");
}
Samples
- ASP.NET Core web app - sign in users
- Windows desktop app (WPF) - sign in users
- Use role-based access control (RBAC) in an application
Explore the full collection of Microsoft identity platform code samples.
Azure SDK for .NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기