包 Microsoft.IdentityModel.Clients.ActiveDirectory 似乎已弃用,我的公司建议迁移到使用 Microsoft.Identity.Client。我需要从我的 AZURE KEY VAULT 检索访问令牌。我可以知道使用 Microsoft.Identity.Client 的替换代码吗?背景:这是一个.Net Framework 4.6.2项目
using Microsoft.IdentityModel.Clients.ActiveDirectory;
private async Task<string> GetTokenAsync(string authority, string resource, string scope)
{
try
{
var authContext = new AuthenticationContext(authority);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource,
new ClientCredential(ClientId, ClientSecret));
if (result == null)
{
throw new InvalidOperationException("Bearer token acquisition needed to call KeyVault service failed");
}
else
{
return result.AccessToken;
}
}
catch (Exception exp)
{
var ex = new Exception(string.Format("Authentication failed for {0}", ClientId), exp);
throw ex;
}
}
你可以这样做:
using Microsoft.Identity.Client;
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithAuthority(authority)
.WithClientSecret(ClientSecret)
.Build();
var result = await app.AcquireTokenForClient(resource).ExecuteAsync();
return result.AccessToken;