When using Identity in ASP.Net Core, it can be useful to seed some data for testing purposes. How to go about that is not entirely obvious, given that the tables involved (IdentityRole, IdentityUser, IdentityUserRole) aren't part of the Entity Framework model you created. However, it is done using the same process you normally follow to seed model data in your ModelContext's OnModelCreating()
override:
protected override void OnModelCreating(ModelBuilder builder)
{
// Your other ModelBuilder stuff goes here (relationships, seed data, etc.)
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// (Apparently you can rename the ASP.NET Identity table names & more, but I haven't done that.)
// Add your customizations AFTER calling base.OnModelCreating(builder);
const string ADMIN_USER_ID = "22e40406-8a9d-2d82-912c-5d6a640ee696";
const string ADMIN_ROLE_ID = "b421e928-0613-9ebd-a64c-f10b6a706e73";
// Add an admin role
builder.Entity<IdentityRole>().HasData(new IdentityRole
{
Id = ADMIN_ROLE_ID,
Name = "admin",
NormalizedName = "ADMIN"
});
// Add a user to be added to the admin role
builder.Entity<IdentityUser>().HasData(new IdentityUser
{
Id = ADMIN_USER_ID,
UserName = "me@example.com",
NormalizedUserName = "ME@EXAMPLE.COM",
Email = "me@example.com",
NormalizedEmail = "ME@EXAMPLE.COM",
EmailConfirmed = true,
PasswordHash = "AQAAAAEAACcQAAAAEIB/N9AG5QrJ4XU3szWuwqgqG7qQ8CMr9dzz3f9F1lB84j0CxarXMAvnA6i0Exj/7Q==",
SecurityStamp = "I5MOLV6IDX2DRGZMNIQ6KEUQKW3QIG3A",
ConcurrencyStamp = "c4736b7b-4dcf-be6b-8b03-e299b4836146"
});
// Add the user to the admin role
builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
RoleId = ADMIN_ROLE_ID,
UserId = ADMIN_USER_ID
});
}
Source: https://stackoverflow.com/q/59229067/4669143 (Although I didn't have to add .AddRoles<IdentityRole>()
, and my Identity setup occurs in ConfigureServices()
in Startup.cs and not IdentityHostingStartup.cs.)