Search code examples
asp.net-mvcasp.net-coreasp.net-identityidentity.net-7.0

How to create User and Role for Admin in .NET 7?


When the database is created, it is empty and I need to have a model for the user in the AspNetUsers table and a role for example admin in AspNetRoles and also in the AspNetUserRoles model these two should be connected to work properly. How to create this item to create them when there is no data in the database.

I have created the user and role model as follows:

User

public class AdminConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        var admin = new User
        {
            Id = "1",
            UserName = "masteradmin",
            NormalizedUserName = "MASTERADMIN",

            Email = "[email protected]",
            NormalizedEmail = "[email protected]",
            PhoneNumber = "XXXXXXXXXXXXX",
            EmailConfirmed = true,
            PhoneNumberConfirmed = true,
            SecurityStamp = new Guid().ToString(),
            Password = "Password"
        };
        admin.PasswordHash = PassGenerate(admin);
        builder.HasData(admin);
    }
    public string PassGenerate(User user)
    {
        var passHash = new PasswordHasher<User>();
        return passHash.HashPassword(user, "password");
    }
}

Role

public class RoleConfiguration : IEntityTypeConfiguration<IdentityRole>
{
    public void Configure(EntityTypeBuilder<IdentityRole> builder)
    {
        var role = new IdentityRole
        {
            Id = "1",
            Name = "Admin",
            ConcurrencyStamp = "b35494cf-4040-47e3-a6de-dee4b6f8e250",
            NormalizedName = "ADMIN",
        };
        builder.HasData(role);
    }
}

and add in DbContext as follows:

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

        ...
        // some codes for the relationship between tables
        ...

        modelBuilder.ApplyConfiguration(new RoleConfiguration());
        modelBuilder.ApplyConfiguration(new AdminConfiguration());

        

    }

I can't populate AspNetUserRoles with this method


Solution

  • In ASP.NET Core Identity, IdentityUserRole is the entity used to represent the relationship between users and roles. You can create a class named UserRoleConfiguration to implement the <IdentityUserRole> interface to complete the binding of role to user. Here is an example that you can use as a reference.

    public class AdminConfiguration : IEntityTypeConfiguration<WebApplication7User>
    {
        public void Configure(EntityTypeBuilder<WebApplication7User> builder)
        {
            var admin = new WebApplication7User
            {
                Id = "2",
                UserName = "masteradmin",
                NormalizedUserName = "MASTERADMIN",
    
                Email = [email protected],
                NormalizedEmail = [email protected],
                PhoneNumber = "XXXXXXXXXXXXX",
                EmailConfirmed = true,
                PhoneNumberConfirmed = true,
                SecurityStamp = new Guid().ToString(),
                PasswordHash = "Password"
            };
            admin.PasswordHash = PassGenerate(admin);
            builder.HasData(admin);
        }
        public string PassGenerate(WebApplication7User user)
        {
            var passHash = new PasswordHasher<WebApplication7User>();
            return passHash.HashPassword(user, "password");
        }
    }
    public class RoleConfiguration : IEntityTypeConfiguration<IdentityRole>
    {
         public void Configure(EntityTypeBuilder<IdentityRole> builder)
         {
             var role = new IdentityRole
             {
                 Id = "2",
                 Name = "Admin",
                 ConcurrencyStamp = "b35494cf-4040-47e3-a6de-dee4b6f8e250",
                 NormalizedName = "ADMIN",
             };
             builder.HasData(role);
         }
    }
    
    public class UserRoleConfiguration : IEntityTypeConfiguration<IdentityUserRole<string>>
    {
        public void Configure(EntityTypeBuilder<IdentityUserRole<string>> builder)
        {
            builder.HasData(
                new IdentityUserRole<string>
                {
                    RoleId = "2",
                    UserId = "2"
                     
                }
            );
        }
    }
    

    My context:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.ApplyConfiguration(new RoleConfiguration());
        builder.ApplyConfiguration(new AdminConfiguration());
        builder.ApplyConfiguration(new UserRoleConfiguration());
    
        base.OnModelCreating(builder);
        
    }
    

    AspNetUsers:

    enter image description here

    AspNetRoles:

    enter image description here

    AspNetUserRoles:

    enter image description here