Ste*_*fan 3 c# asp.net azure-ad-msal
var scope = AzureAdB2COptions.ApiScopes.Split(' ');
string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, AzureAdB2COptions.ApiUrl);
// Add token to the Authorization header and make the request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
使用 Microsoft Identity Client 1.0,示例代码运行完美。更新到 Microsoft Identity Client 2.7 后,我出现了两个错误
ClientApplicationBase.Users' 已过时:'使用 GetAccountsAsync 代替(参见 https://aka.ms/msal-net-2-released)' WebApp-OpenIDConnect-DotNet C:\Users\IDE00053\Downloads\active-directory-b2c- dotnetcore-webapp-master\WebApp-OpenIDConnect-DotNet\Controllers\HomeController.cs
和
参数 2:无法从“Microsoft.Identity.Client.IUser”转换为“Microsoft.Identity.Client.IAccount” WebApp-OpenIDConnect-DotNet C:\Users\IDE00053\Downloads\active-directory-b2c-dotnetcore-webapp-master \WebApp-OpenIDConnect-DotNet\Controllers\HomeController.cs
在代码行
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false);
Run Code Online (Sandbox Code Playgroud)
感谢帮助斯蒂芬
小智 5
MSALv1 和 v2 之间进行了一些更改。这是博客文章,详细介绍了两者之间的差异。如错误消息中所述,具有类型的字段或属性的类型IUser现在引用IAccount. 并ClientApplicationBase.Users成为GetAccountsAsync()。根据您的代码,您需要这样的东西:
IEnumerable<IAccount> accounts = await app.GetAccountsAsync();
IAccount firstAccount = accounts.FirstOrDefault();
try
{
result = await app.AcquireTokenSilentAsync(scopes, firstAccount);
}
catch (MsalUiRequiredException)
{
result = await app.AcquireTokenAsync(scopes, firstAccount);
}
accounts = await app.GetAccountsAsync();
firstAccount = accounts.FirstOrDefault();
IAccount me = await app.GetAccountAsync(firstAccount.HomeAccountId.Identifier);
Run Code Online (Sandbox Code Playgroud)
这是已更新到 MSAL v2的B2C 示例。
该团队还致力于对公共 API (MSAL v3) 进行进一步更改,可在此处查看。