Skip to content

Instantly share code, notes, and snippets.

@HugoVG
Created July 23, 2022 14:13
Show Gist options
  • Save HugoVG/8ae09a4364932ed9cbe8f971afad6c35 to your computer and use it in GitHub Desktop.
Save HugoVG/8ae09a4364932ed9cbe8f971afad6c35 to your computer and use it in GitHub Desktop.
Seeding an identity database with a super user
CreateDatabase();
using (var scope = app.Services.CreateScope()) //Creates a new scope
{
//Resolve ASP .NET Core Identity with DI help
var roleManager = (RoleManager<IdentityRole>)scope.ServiceProvider.GetService<RoleManager<IdentityRole>>(); //gets services
var userManager = (UserManager<IdentityUser>)scope.ServiceProvider.GetService<UserManager<IdentityUser>>();
CreateRolesAsync(roleManager).Wait();
CreateSuperUser(userManager).Wait();
}
//important that this is called after these
app.UseAuthentication();
app.UseAuthorization();
//rest of the app builder code
app.run()
//Rest of the code
void CreateDatabase() //Makes sure the database exists
{
using (var serviceScope = app.Services.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
}
async Task CreateRolesAsync(RoleManager<IdentityRole> roleManager)
{
string[] roleNames = { "Admin", "Member", "<<Secondary role>>" }; //All role names that will be inserted
foreach (var roleName in roleNames) // loops through all the the role names
{
var roleExist = await roleManager.RoleExistsAsync(roleName); // and makes roles if they are not there
if (!roleExist)
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
async Task CreateSuperUser(UserManager<IdentityUser> userManager) //Uses the scoped Manager
{
var superUser = new IdentityUser { Email = "<<Email>>", UserName = "<<Username>>", EmailConfirmed = true, };
await userManager.CreateAsync(superUser, "<<Password>>");
var token = await userManager.GenerateEmailConfirmationTokenAsync(superUser); //Only needed if Confirm email is on
await userManager.ConfirmEmailAsync(superUser, token); //Auto confirms the email
await userManager.AddToRoleAsync(superUser, "Admin"); //Adds the roles to the super user
await userManager.AddToRoleAsync(superUser, "Member");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment