gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:06:24 24 4
gpt4 key购买 nike

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

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

应在 View 中从 User.Identity.Name 属性中读取此值。

User.Identity.Name

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

context

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

userPrincipal

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

httoContext

我已经尝试执行手动登录,但这也不起作用:

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
});
}

更新

name

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

有人知道我做错了什么吗?

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

最佳答案

您是否在OpenIdConnectOptions 配置中设置了NameClaimType:

options.TokenValidationParameters = new TokenValidationParameters() { NameClaimType = "name" };

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

  1. 安装 Microsoft.Identity.Client 2.7 版
  2. 从代码示例中复制 MSALSessionCacheAzureAdB2COptionsOpenIdConnectOptionsSetup
  3. 根据代码示例的配置更新Startup.csappsettings.json

我没有创建自己的应用程序和 Api,只是使用代码示例提供的 fabrikamb2cdomain,即使某些方法在 .net core 2.2 中已过时,例如 cache。已更改 。身份验证仍然有效,并使用 User.Identity.Name 获得正确的名称,还设置了 HttpContext.User.Claims :

enter image description here

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

关于c# - 使用 aspnetcore 2.2 联合 Azure AD 登录后,User.Identity.Name 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54444747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com