asp.net-mvc - 在与 Azure AD B2C 集成的网站中获取访问 token

标签 asp.net-mvc azure asp.net-core azure-ad-b2c

我有一个 ASP.NET MVC Core 2.2 应用程序,它与 Azure AD B2C 集成以对用户进行身份验证。我可以正确登录,并且用户已通过身份验证。

我还创建了一个 ASP.NET Core Web API,它也与 Azure B2C AD 集成,目标是从 ASP.NET MVC Controller 操作方法调用该 Web API。

所以我在MVC站点的 Controller 中添加了以下测试代码:

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。不知道为什么:

有人知道我做错了什么吗?感谢您的任何提示!

额外观察:如果我运行演示 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(),这将返回no帐户。

最佳答案

.NETCore B2C web app已更新为使用 MSAL v2.7。使用的范围不正确,因此示例现在使用正确的范围并返回访问 token 。

“ApiScopes”:“https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read”

关于asp.net-mvc - 在与 Azure AD B2C 集成的网站中获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335269/

相关文章:

c# - 如何使用 Angular 取消 .Net Core Web API 请求?

angularjs - ASP.NET 5 中的 URL 重写

asp.net-core - 在运行时加载 nuget 包及其程序集

c# - 如何防止 ASP.net MVC 应用程序通过域身份验证?

c# - C#中传入 "Parameter Sets"

jquery - 使用 Jquery Ajax 将模型从 View 传递到 Controller

python - 将tensorflow添加到requirements.txt时,Azure Python Function App部署失败

azure - Cosmos db graph 与 Azure Sql Server - 性能和成本

c# - EntityType 没有在 MVC 4 中定义的键

azure - Blob 在 Azure 存储帐户中保留多长时间?