gpt4 book ai didi

c# - 在 MVC 中使用 Azure Active Directory 登录后如何添加和访问其他属性?

转载 作者:行者123 更新时间:2023-11-30 17:34:49 25 4
gpt4 key购买 nike

我已设置 Azure Active Directory (AD) 来登录 MVC Web 应用程序。登录后,Azure 仅返回电子邮件 ID。我需要扩展它以使用电子邮件 ID 作为关键字段来获取一些基本属性;映射 AD 和我的数据库,其中包含其他详细信息。

我的要求如下

  1. 需要使用AD登录。
  2. 登录 Azure 后将返回电子邮件 ID(可以从 HttpContext.User.Identity.Name 访问),我需要在登录期间从数据库中获取一些与配置文件相关的其他属性,并存储在扩展身份中。
  3. 我不想每次执行操作时都从数据库中获取这些附加详细信息,相反,我需要在用户登录后从数据库中获取这些附加属性,就像 MVC 正常身份验证一样。
  4. AD Graph API 没有用,因为我不想在 Azure 中存储其他详细信息,而是可以在我的数据库中使用。

最佳答案

如果您使用 OpenIdConnect 的 OWIN 中间件,则可以在中间件验证 token 后将自定义数据添加为自定义声明。

所以类似:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Rest of config left out for brevity
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async (notification) =>
{
ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
//Get the user data any way you want
//Add claims
identity.AddClaim(new Claim("homeTown", "Somewhere"));
}
}
});

ClaimsIdentity 将包含有关登录用户的常用用户信息。您可以在此处添加任何您想要的声明,它们将像通常的声明一样存储。然后您可以访问这些声明,例如通过 User 属性或通过其他任何地方的 ClaimsPrincipal.Current 在您的 Controller 中。

这里的主要优点是,您只需在用户登录时获取一次数据,无需在每个请求中获取它们。

关于c# - 在 MVC 中使用 Azure Active Directory 登录后如何添加和访问其他属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918240/

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