Для работы с учётными записями пользователей и разграничения доступа по ролям в распоряжении ASP.NET Core MVC имеется специальная библиотека Identity. С её помощь также можно создать так называемых пользователей по умолчанию. Учётные записи, которые присутствуют в приложении изначально и позволяют начать работу с ним сразу же после развёртывания.
Перед тем как создавать пользователей, необходимо создать их роли (если предполагается разделение по ролям). Для этого используется стандартный класс RoleManager из библиотеки Identity.
1 2 3 4 |
if (await roleManager.FindByNameAsync("admin") == null) { await roleManager.CreateAsync(new IdentityRole("admin")); } |
По аналогии для создания пользователей используется UserManager. Чтобы создать пользователя, помимо роли, нам потребуется его email, логин (UserName) и пароль.
1 2 3 4 5 6 7 8 9 10 11 |
string adminEmail = "admin@example.com"; if (await userManager.FindByNameAsync(adminEmail) == null) { tring password = "Admin1!"; IdentityUser admin = new IdentityUser { Email = adminEmail, UserName = adminEmail }; IdentityResult result = await userManager.CreateAsync(admin, password); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, "admin"); } } |
Обратите внимание, что перед созданием роли и пользователя очень желательно выполнить проверку их существования, как это показано в примерах выше, так как в Identity не допускается наличие одновременно двух одинаковых ролей или пользователей.
Ниже приведён пример класса, который создаёт три роли (администратор, продавец и покупатель) и три пользователя (по одному для каждой из ролей).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class UserInitializer { private const string AdminRoleName = "admin"; private const string SellerRoleName = "seller"; private const string BuyerRoleName = "buyer"; private const string AdminUserEmail = "admin@example.com"; private const string SellerUserEmail = "seller@example.com"; private const string BuyerUserEmail = "buyer@example.com"; private const string AdminUserPassword = "Admin1!"; private const string SellerUserPassword = "Seller2@"; private const string BuyerUserPassword = "Buyer3#"; public static async Task InitializeAsync(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager) { await CreateRole(roleManager, AdminRoleName); await CreateRole(roleManager, SellerRoleName); await CreateRole(roleManager, BuyerRoleName); await CreateUser(userManager, AdminUserEmail, AdminUserPassword, AdminRoleName); await CreateUser(userManager, SellerUserEmail, SellerUserPassword, SellerRoleName); await CreateUser(userManager, BuyerUserEmail, BuyerUserPassword, BuyerRoleName); } private static async Task CreateUser(UserManager<IdentityUser> userManager, string userEmail, string userPassword, string roleName) { if (await userManager.FindByNameAsync(userEmail) == null) { IdentityUser admin = new IdentityUser { Email = userEmail, UserName = userEmail }; IdentityResult result = await userManager.CreateAsync(admin, userPassword); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, roleName); } } } private static async Task CreateRole(RoleManager<IdentityRole> roleManager, string roleName) { if (await roleManager.FindByNameAsync(roleName) == null) { await roleManager.CreateAsync(new IdentityRole(roleName)); } } } |
Для того чтобы воспользоваться этим классом нужно вызвать его метод InitializeAsync в одной из миграций или, как показано в примере ниже в методе Main класса Program. Последнее обеспечивает автоматическую проверку существования соответствующих ролей и пользователей и их автоматическое создание при каждом запуске.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class Program { public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); InitializeUsers(host); host.Run(); } private static async Task InitializeUsers(IWebHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var userManager = services.GetRequiredService<UserManager<IdentityUser>>(); var rolesManager = services.GetRequiredService<RoleManager<IdentityRole>>(); await UserInitializer.InitializeAsync(userManager, rolesManager); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while seeding the database."); } } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } |
Добавить комментарий