4using Microsoft.AspNetCore.Identity;
11var
builder = WebApplication.CreateBuilder(args);
15builder.WebHost.ConfigureKestrel(options =>
17 options.Limits.MaxRequestBodySize = 104_857_600;
23builder.Logging.AddFilter(
"Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
33builder.Services.AddEndpointsApiExplorer();
55app.UseExceptionHandler();
58if (
app.Environment.IsDevelopment())
67app.UseCors(
"AllowClient");
69app.UseHttpsRedirection();
71app.UseAuthentication();
73app.UseAuthorization();
83 using var scope = services.CreateScope();
84 var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
86 string[] roles = {
"Admin",
"User" };
88 foreach (var role
in roles)
90 if (!await roleManager.RoleExistsAsync(role))
92 await roleManager.CreateAsync(
new IdentityRole(role));
100 using var scope = services.CreateScope();
101 var userManager = scope.ServiceProvider.GetRequiredService<UserManager<LoginUser>>();
102 var
configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
103 var adminUsers =
configuration.GetSection(
"AdminUsers").Get<List<AdminUserConfig>>();
105 if (adminUsers ==
null || !adminUsers.Any())
107 Console.WriteLine(
"No admin users configured.");
111 Console.WriteLine(
"Creating Default Admin Accounts...");
113 foreach (var adminConfig
in adminUsers)
115 if (
string.IsNullOrEmpty(adminConfig.Email) ||
string.IsNullOrEmpty(adminConfig.Password))
continue;
117 if (await userManager.FindByEmailAsync(adminConfig.Email) ==
null)
119 var salt = System.Security.Cryptography.RandomNumberGenerator.GetBytes(16);
123 UserName = adminConfig.Email,
124 Email = adminConfig.Email,
125 EmailConfirmed =
true,
129 var result = await userManager.CreateAsync(adminUser, adminConfig.Password);
131 if (result.Succeeded)
133 await userManager.AddToRoleAsync(adminUser,
"Admin");
134 await userManager.AddToRoleAsync(adminUser,
"User");
135 Console.WriteLine($
"Admin User '{adminConfig.Email}' created successfully.");
144internal class AdminUserConfig
146 public string? Email {
get;
set; }
147 public string? Password {
get;
set; }
LoginUser extends the IdentityUser class to include additional properties specific to the application...
await CreateDefaultAdminsAsync(app.Services)
await SeedRolesAsync(app.Services)