asp.net-mvc - 在与 Azure AD B2C 集成的网站中获取访问令牌
问题描述
我有一个 ASP.NET MVC Core 2.2 应用程序,它与 Azure AD B2C 集成以对用户进行身份验证。我可以正确登录,并且用户已通过身份验证。
我还创建了一个 ASP.NET Core Web API,它也与 Azure B2C AD 集成,目标是从 ASP.NET MVC 控制器操作方法调用该 Web API。
于是我在MVC站点的控制器中添加了如下测试代码:
if (HttpContext.User.Identity.IsAuthenticated)
{
string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(mgpPortalApplicationId, authority, redirectUri, new ClientCredential(mgpPortalSecretKey), userTokenCache, null);
IEnumerable<IAccount> accounts = await cca.GetAccountsAsync();
IAccount firstAccount = accounts.FirstOrDefault();
AuthenticationResult result = await cca.AcquireTokenSilentAsync(null, firstAccount, authority, false);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44307/api/values");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
}
问题是accounts.FirstOrDefault()
返回null。不知道为什么:
- signedInUserID 包含登录用户的标识符
- mgpPortalApplicationId 是 MVC 站点的应用程序 ID
- 权限是“ https://login.microsoftonline.com/tfp/primfoodcareb2c.onmicrosoft.com/B2C_1_mgpsignupsignin/v2.0 ”
- redirectUri 是“ https://localhost:44355/signin-oidc ”
- mgpPortalSecretKey 包含我将 MVC 应用程序添加到 B2C 租户时生成的密钥
有人知道我做错了什么吗?感谢您的任何提示!
附加观察:如果我运行演示https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp,它使用较旧的 Microsoft.Identity.Client,然后调用 cca.Users.FirstOrDefault( ) 正确回馈用户。但是,当我将此演示项目升级到 Microsoft.Identity.Client 2.7(.NET Core 2.2 需要它)时,我必须传递一个 IAccount ,所以我需要调用GetAccountsAsync()
,这不会返回任何帐户。
解决方案
.NETCore B2C Web 应用已更新为使用 MSAL v2.7。使用的范围不正确,因此示例现在使用正确的范围并返回访问令牌。
"ApiScopes": "https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"