I wonder if it's possible to add users and passwords without have to register them with a form.
I have an existing DB with some users and passwords and I want to transfer it to aspNetUser
.
I migrated these default tables into local DB and I don't understand how to set about 10 existing users with only passwords in these tables.
I only want to "paste" in users and passwords.
I'm using Blazor server template with individual authentication enable.
CodePudding user response:
Yes, you can do that but manually as a seed to your database.
You can do something like that:
public class AppIdentityDbContextSeed
{
public static async Task SeedAsync(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
await roleManager.CreateAsync(new IdentityRole("Administrators"));
var defaultUser = new IdentityUser { UserName = "your username", Email = "your email" };
await userManager.CreateAsync(defaultUser, "your password");
string adminUserName = "Your admin name";
var adminUser = new IdentityUser { UserName = adminUserName, Email = "your admin email" };
await userManager.CreateAsync(adminUser, "your admin password");
adminUser = await userManager.FindByNameAsync(adminUserName);
await userManager.AddToRoleAsync(adminUser, "Administrators");
}
}
Then you can use SeedAsync
method in your program
class as below:
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args)
.Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager);
}
catch (Exception ex)
{
//exception handling
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Finally check Startup.cs
, it should be as below:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();