扩展Identity 2.2.1以存储自定义数据

本文关键字:自定义 数据 存储 Identity 扩展 | 更新日期: 2023-09-27 18:08:21

目前在Identity 2.2.1中,可以使用User。检索用户id和用户名的标识:

string ID = User.Identity.GetUserId();
string Name = User.Identity.Name;

然而,我想将其扩展到User.Identity.FullName, User.Identity.FirstName等。

我尝试创建自定义IIdentity和IPrincipal类,然后设置FormAuthentication cookie。这我认为是错误的方式去,因为它然后创建冲突与DefaultAuthenticationTypes.ApplicationCookie。http://problemfacing.blogspot.in/2013/07/aspnet-mvc-set-custom-iidentity-or.html

还可以查看claimsIdentity。我无法使它在Identity 2.2.1中工作,而2.0和2.1有很多解决方案

谁能告诉我一个优雅的,简单的方法来实现这个身份2.2.1?

扩展Identity 2.2.1以存储自定义数据

你可以像这样在你的ApplicationUser中添加这些属性作为Claims:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var identity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        var user = this;
        // Add Full Name, Firstname etc....
        identity.AddClaim(new Claim("FullName", user.FirstName + ' ' + user.LastName));
    }
}

这样你就可以访问这些声明,而不必访问数据库。

如果您希望扩展您的User类,那么您可以为Identity或Principal创建扩展方法。下面是一个例子:

public class UserPrincipal : ClaimsPrincipal
{
    public UserPrincipal(ClaimsPrincipal principal)
        : base(principal)
    {
    }
    /// <summary>
    /// Full Name of current logged in user.
    /// </summary>
    public string FullName
    {
        get
        {
            return this.FindFirst("FullName").Value ?? string.Empty;
        }
    }
}

现在你可以在你的控制器中创建一个方法来访问FullName(像这样):

    private UserPrincipal CurrentUser
    {
        get
        {
            return new UserPrincipal(base.User as ClaimsPrincipal);
        }
    }

现在你可以在你的控制器中使用CurrentUser.FullName

如果你想抽象它,你可以创建一个BaseController类:

public class BaseController : Controller
{
    public UserPrincipal CurrentUser
    {
        get
        {
            return new UserPrincipal(base.User as ClaimsPrincipal);
        }
    }
}

和继承BaseController而不是Controller在所有的控制器

为Identity创建自定义用户非常容易。

第一步是创建User,它将保存您的自定义字段,并从Microsoft.AspNet.Identity.EntityFramework命名空间中的IdentityUser派生它:

public class MyUser : IdentityUser
{
    public string FirstName{ get; set; }
    public string LastName { get; set; }
}

然后你需要通过从Identity的UserManager派生出你的自定义UserManager

public class UserManager : UserManager<MyUser>
{
    public UserManager(Context context, IUserTokenProvider<MyUser, string> tokenProvider = null)
        : base(new MyUserStore(context))
    {
        UserTokenProvider = tokenProvider;
        UserValidator = new UserValidator<MyUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        PasswordValidator = new PasswordValidator
        {
            RequireDigit = false,
            RequireLowercase = false,
            RequireNonLetterOrDigit = false,
            RequireUppercase = false,
            RequiredLength = 2
        };
    }
}

最后,你应该创建一个自定义的UserStore从默认的派生:

public class MyUserStore : UserStore<MyUser>
{
    public MyUserStore(Context context)
        : base(context)
    {
    }
}

您可以通过添加扩展方法来实现:

public static class IdentityExtention
{
   public static string FullName(this System.Security.Principal.IIdentity user)
   {
            return // return fullName from database;
   }
}

然后你可以很容易地在你的视图中使用它:

User.Identity.FullName()