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

Bha*_*rat 5 c# asp.net-mvc active-directory azure asp.net-identity

我已经设置了 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 中存储其他详细信息,而是在我的数据库中可用。

juu*_*nas 1

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

所以像这样:

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"));
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

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

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