使用 aspnetcore 2.2 联合 Azure AD 登录后,User.Identity.Name 为空

oss*_*too 4 c# httpcontext claims-based-identity azure-ad-b2c asp.net-core

我尽可能地遵循 AzureAD aspnetcore 示例,尝试在我们的 aspnetcore 2.2 webapp 中实现 Azure AD 身份验证。我可以使用 Azure AD 成功登录。但是,登录后不会显示用户名。

https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp

该值应该从 User.Identity.Name 属性的视图中读取。

用户.身份.名称

在进一步检查中,我可以看到主要索赔已正确返回到应用程序。但是,由于某种原因 HttpContext.User 对象未正确填充。我不知道为什么会这样。当我从上面的示例中查看相同的值时,HttpContext 设置正确。为了澄清起见,我已经实现了 OnSecurityTokenValidated 处理程序并使用了以下上下文:

语境

可以看出, userPrincipal 具有预期的声明。

用户主体

但是,httpContext 没有声明。因此 User.Identity.Name 也为空:

上下文

我试图进行手动登录,但这也不起作用:

private async Task SignInUser(TokenValidatedContext tokenValidatedContext)
{
    var httpContext = tokenValidatedContext.HttpContext;
    var userPrincipal = tokenValidatedContext.Principal;

    await httpContext.SignOutAsync(AppSettings.CookieName);
    await httpContext.SignInAsync(AppSettings.CookieName, userPrincipal,
      new AuthenticationProperties
      {
          ExpiresUtc = DateTime.UtcNow.AddDays(1),
          IsPersistent = false,
          AllowRefresh = false
      });
}
Run Code Online (Sandbox Code Playgroud)

更新

姓名

我正在设置 NameClaimType,如上所示。NameClaimType 在配置中设置

任何人都知道我做错了什么?

我正在使用 Visual Studio 2017 和 aspnetcore 2.2 库。我已将 Microsoft.Identity.Client 升级到 2.7

Nan*_* Yu 5

您是否NameClaimTypeOpenIdConnectOptions配置中设置:

options.TokenValidationParameters = new TokenValidationParameters() { NameClaimType = "name" };
Run Code Online (Sandbox Code Playgroud)

为了测试场景,我使用默认的 MVC 模板创建了一个新的 asp.net core 2.2 应用程序:

  1. 安装 Microsoft.Identity.Client 版本 2.7
  2. 复制代码示例中的MSALSessionCache, AzureAdB2COptions,OpenIdConnectOptionsSetup
  3. 更新Startup.csappsettings.json基于代码示例的配置。

我还没有创建自己的应用程序和 Api,只是使用fabrikamb2c域作为代码示例提供的,即使某些方法在 .net core 2.2 中已经过时,例如,cache.HasStateChanged。身份验证仍然有效并使用 获得正确名称User.Identity.NameHttpContext.User.Claims也可以设置:

在此处输入图片说明

您可以提供更多详细信息以帮助重现您的问题。