Adding columns to AspNetUserClaims in ASP.NET Identity

筅森魡賤 提交于 2019-12-11 08:03:33

问题


I'm using Microsoft.AspNet.Identity.Core 2.2.1 in my solution. I need to integrate this with another system that should automatically add claims.

In order to keep track of which claims are manually added and which are created by an external system, I would like another column on my AspNetUserClaims table:

ExternalSystem varchar(64) null

How do I do this using EF Migrations (or without if nescessary), seeing as I don't actually have the claims class in my solution?


回答1:


You can create our own custom app user claim class which is derived from IdentityUserClaim class and add custom fields.

public class ApplicationUserClaim : IdentityUserClaim
{
    public ApplicationUserClaim() { }

    public ApplicationUserClaim(string userId, string claimType,
        string claimValue, string externalSystem)
    {
        UserId = userId;
        ClaimType = claimType;
        ClaimValue = claimValue;
        ExternalSystem = externalSystem;
    }

    [MaxLength(64)]
    public string ExternalSystem { get; set; }
}

After that, you need to configure ApplicationDbContext and ApplicationUser classes like:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string,
        IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    // ...
}

public class ApplicationUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    // ...
}

Additionally, you have to create custom UserStore class like:

public class ApplicationUserStore : UserStore<ApplicationUser, IdentityRole, string,
        IdentityUserLogin, IdentityUserRole, ApplicationUserClaim>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }
} 

And then you can use ApplicationUserManager like:

var ctx = new ApplicationDbContext();
var manager = new ApplicationUserManager(new ApplicationUserStore(ctx));


来源:https://stackoverflow.com/questions/42998020/adding-columns-to-aspnetuserclaims-in-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!