I have an ASP.NET MVC Core 2.2 application, that integrates with an Azure AD B2C to authenticate users. I can sign in correctly, and the user is authenticated.
I also have created an ASP.NET Core Web API which is also integrated with the Azure B2C AD, and the goal is to call that web api from an ASP.NET MVC controller action method.
So I added the following test code in the controller of the MVC site:
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);
}
The problem is that accounts.FirstOrDefault()
gives back null. Not sure why:
- signedInUserID contains the identifier of the logged on user
- mgpPortalApplicationId is the application ID of the MVC site
- authority is "https://login.microsoftonline.com/tfp/primfoodcareb2c.onmicrosoft.com/B2C_1_mgpsignupsignin/v2.0"
- redirectUri is "https://localhost:44355/signin-oidc"
- mgpPortalSecretKey contains the secret that was generated when I added the MVC application to the B2C tenant
Does anyone have an idea on what I'm doing wrong? Thanks for any hints!
Additional observation: if I run the demo https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp, which uses an older Microsoft.Identity.Client, then the call to cca.Users.FirstOrDefault() gives back a user correctly. However, when I upgrade this demo project to Microsoft.Identity.Client 2.7 (which is needed for .NET Core 2.2), then I have to pass an IAccount and so I need to call GetAccountsAsync()
, and this returns no account.