如何从表 AspNetUsers 在标识 2.2.1 中添加另一个属性到用户身份

本文关键字:另一个 添加 属性 身份 用户 AspNetUsers 标识 | 更新日期: 2023-09-27 18:33:33

i 首先向标识 2.2.1 (AspNetUsers 表) 代码添加一些新 asp.net 属性

 public class ApplicationUser : IdentityUser
    {
        public string AccessToken { get; set; }
        public string FullName { get; set; }
        public string ProfilePicture { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

好的,现在我想调用个人资料图片,例如以下代码:User.Identity.ProfilePicture;

解决方案是:

您需要创建自己的类来实现 IIdentity 和 伊普林西帕尔。然后在您的 global.asax 中分配它们 在邮政身份验证。

但我不知道该怎么做!! 如何创建我自己的实现 IIdentity 和 IPrincipal 的类。然后在 OnPostAuthenticate 的 global.asax 中分配它们。谢谢。

如何从表 AspNetUsers 在标识 2.2.1 中添加另一个属性到用户身份

您有 2 个选项(至少)。首先,在用户登录时将附加属性设置为声明,然后在每次需要时从声明中读取属性。其次,每次需要属性时,都会从存储 (DB) 中读取它。虽然我推荐基于声明的方法,这种方法更快,但我将使用扩展方法向您展示这两种方法。

第一种方法:

将您自己的声明放入GenerateUserIdentityAsync方法中,如下所示:

public class ApplicationUser : IdentityUser
{
    // some code here
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("ProfilePicture", this.ProfilePicture));
        return userIdentity;
    }
}

然后编写一个扩展方法来轻松读取声明,如下所示:

public static class IdentityHelper
{
    public static string GetProfilePicture(this IIdentity identity)
    {
        var claimIdent = identity as ClaimsIdentity;
        return claimIdent != null
            && claimIdent.HasClaim(c => c.Type == "ProfilePicture")
            ? claimIdent.FindFirst("ProfilePicture").Value
            : string.Empty;
    }
}

现在,您可以像这样轻松使用扩展方法:

var pic = User.Identity.GetProfilePicture();

第二种方法:

如果您更喜欢新数据而不是索赔中的兑现数据,则可以编写另一个扩展方法来从用户管理器获取属性:

public static class IdentityHelper
{
    public static string GetFreshProfilePicture(this IIdentity identity)
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        return userManager.FindById(identity.GetUserId()).ProfilePicture;
    }
}

现在只需像这样使用:

var pic = User.Identity.GetFreshProfilePicture();

另外不要忘记添加相关的命名空间:

using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;