Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding columns to AspNetUserClaims in ASP.NET Identity

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?

like image 273
Troels Larsen Avatar asked Mar 10 '23 12:03

Troels Larsen


1 Answers

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));
like image 87
Gedao Avatar answered Mar 21 '23 03:03

Gedao