c# - 如何使用 Microsoft 身份验证库 (MSAL) 通过 AD 应用 ClientId 和 Client Secret 获取 token

标签 c# azure azure-ad-msal azure-adal-deprecation

旧版 ADAL 库通过 Client App ID 和 Client Secret 获取 token ,例如:

var clientID = "";
var clientSecret = "";
var aadTenantDomain = "tenant domain";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", aadTenantDomain), false);
var clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientID, clientSecret);
var authenticationResult = await context.AcquireTokenAsync("https://graph.microsoft.com", clientCred).ConfigureAwait(false);
return authenticationResult.AccessToken;

给定 AD 应用 ClientId 和客户端 key ,如何使用 MSAL 获取访问 token ?

谢谢!

最佳答案

引用下面的代码从客户端 ID 和客户端 key 获取访问 token 。

代码:-

using Microsoft.Identity.Client;

var clientID = "xxxxxxxx-xxxx-45b5-b838-6d26a31435cb";
var clientSecret = "xxxxxxxxxxxxxxxxxxxHiOEM6fDAQQ7BNiOLPaH.";
var aadTenantDomain = "xxxxxxxsaioutlook.onmicrosoft.com";
var authority = $"https://login.microsoftonline.com/{aadTenantDomain}";
var clientApplication = ConfidentialClientApplicationBuilder.Create(clientID)
  .WithClientSecret(clientSecret)
  .WithAuthority(authority)
  .Build();
var scopes = new string[] { "https://graph.microsoft.com/.default" };
var authenticationResult = await clientApplication.AcquireTokenForClient(scopes)
  .ExecuteAsync()
  .ConfigureAwait(false);
var accesstoken = authenticationResult.AccessToken;
Console.WriteLine(accesstoken);

输出:-

enter image description here

关于c# - 如何使用 Microsoft 身份验证库 (MSAL) 通过 AD 应用 ClientId 和 Client Secret 获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75394006/

相关文章:

重复模式的 C# 正则表达式

c# - 将 GraphQL 查询映射到 Select() linq 到 sql

c# - 读取作为 blob 上传的 azure 中的 excelsheet

azure - 向 Azure 进行身份验证时的自定义应用程序权限和授权

xamarin - 使用 Xamarin 和 Azure AD B2C 设置自定义选项卡的样式

c# - jquery 中的 insidehtml 等效项不起作用

Azure 事件目录 | Multi-Tenancy 应用

Azure 存储 Blob : what kind of blob do I get with GetBlobReference()?

azure - 代表 api(而非用户)从另一个 Web Api 获取 401 Unauthorized Calling Web Api

c# - Linq ToList() 无法触发立即执行