How do I seed a \"admin\" user role when identity is scaffolded?
I would like to find my power-user account by email and seed the admin role. Most examples I find us
a bit old thread but this may help anyone seeking it. You can seed Users and Roles in OnModelCreating() method inside IdentityDbContext.cs file as shown below. Note that the keys should be predefined to avoid seeding new users and new roles everytime this method is executed:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//Seeding a 'Administrator' role to AspNetRoles table
modelBuilder.Entity().HasData(new IdentityRole {Id = "2c5e174e-3b0e-446f-86af-483d56fd7210", Name = "Administrator", NormalizedName = "ADMINISTRATOR".ToUpper() });
//a hasher to hash the password before seeding the user to the db
var hasher = new PasswordHasher();
//Seeding the User to AspNetUsers table
modelBuilder.Entity().HasData(
new IdentityUser
{
Id = "8e445865-a24d-4543-a6c6-9443d048cdb9", // primary key
UserName = "myuser",
NormalizedUserName = "MYUSER",
PasswordHash = hasher.HashPassword(null, "Pa$$w0rd")
}
);
//Seeding the relation between our user and role to AspNetUserRoles table
modelBuilder.Entity>().HasData(
new IdentityUserRole
{
RoleId = "2c5e174e-3b0e-446f-86af-483d56fd7210",
UserId = "8e445865-a24d-4543-a6c6-9443d048cdb9"
}
);
}