Search code examples
asp.net-coreentity-framework-coreasp.net-identityclaims-based-identity

Add claims to admin when db is launched first time


Admin account have to be added when db is launched first time. I added User with name "admin", but dont know how to attach claims to it.

ApplicationDbContext:

...
protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        var hasher = new PasswordHasher<User>();
        modelBuilder.Entity<User>().HasData(
            new User 
            {
                UserName = "admin",
                PasswordHash = hasher.HashPassword(null!, "admin"),
       
                FirstName = "FirstName",
                LastName = "LastName",
                NormalizedUserName = "admin".ToUpper(),
                Email = "[email protected]",
                NormalizedEmail = "[email protected]".ToUpper(),
                EmailConfirmed = true
            });
    }
...

I can add claim to IdentityUserClaims manually. But then I need to attach that claim to created User somehow. I can use UserId from IdentityUserClaims but UserId is generating automatically. It looks like "e23cfc12-22b0-4f3a-9229-a4d606f3ecf0" when I use UserManager to add claims. So attaching claims manually is not good idea.

modelBuilder.Entity<IdentityUserClaim<string>>().HasData(
            new IdentityUserClaim<string>
            {
                Id = 1,
                UserId = "??????",
                ClaimType = ClaimTypes.Role,
                ClaimValue = "admin"
            },

Solution

  • So when you create user just add Id

                modelBuilder.Entity<IdentityUser>().HasData(
                    new IdentityUser
                    {
                        Id= "e23cfc12-22b0-4f3a-9229-a4d606f3ecf0",
                        UserName = "admin",
                        ...
    

    Then you could use this Id as UserId when create IdentityUserClaim

                modelBuilder.Entity<IdentityUserClaim<string>>().HasData(
                new IdentityUserClaim<string>
                {
                    Id = 1,
                    UserId = "e23cfc12-22b0-4f3a-9229-a4d606f3ecf0",
                    ...