How to Seed Users and Roles with Code First Migration using Identity ASP.NET Core

前端 未结 10 1566
离开以前
离开以前 2020-12-04 10:12

I have created a new clean asp.net 5 project (rc1-final). Using Identity Authentication I just have the ApplicationDbContext.cs with the following code:

publ         


        
10条回答
  •  孤街浪徒
    2020-12-04 10:51

    In aspnetcore there is the concept of IHostedService. This makes it possible to run async background Task.

    The solution of @hamid-mosalla could be made async and called from an IHostedService implementation.

    Seed class implementation could be something like

    public class IdentityDataSeeder
    {
        private readonly UserManager _userManager;
        private readonly RoleManager _roleManager;
    
        public IdentityDataSeeder(
            UserManager userManager,
            RoleManager roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }
    
        public async Task SeedAsync()
        {
            var superAdminRole = new IdentityRole
            {
                Id = "cac43a6e-f7bb-4448-baaf-1add431ccbbf",
                Name = "SuperAdmin",
                NormalizedName = "SUPERADMIN"
            };
            await CreateRoleAsync(superAdminRole);
    
            var superAdminUserPassword = "P@ssword1";
            var superAdminUser = new ApplicationUser
            {
                Id = "b8633e2d-a33b-45e6-8329-1958b3252bbd",
                UserName = "admin@example.nl",
                NormalizedUserName = "ADMIN@EXAMPLE.NL",
                Email = "admin@example.nl",
                NormalizedEmail = "ADMIN@EXAMPLE.NL",
                EmailConfirmed = true,
            };
            await CreateUserAsync(superAdminUser, superAdminUserPassword);
    
            var superAdminInRole = await _userManager.IsInRoleAsync(superAdminUser, superAdminRole.Name);
            if (!superAdminInRole)
                await _userManager.AddToRoleAsync(superAdminUser, superAdminRole.Name);
        }
    
        private async Task CreateRoleAsync(IdentityRole role)
        {
            var exits = await _roleManager.RoleExistsAsync(role.Name);
            if (!exits)
                await _roleManager.CreateAsync(role);
        }
    
        private async Task CreateUserAsync(ApplicationUser user, string password)
        {
            var exists = await _userManager.FindByEmailAsync(user.Email);
            if (exists == null)
                await _userManager.CreateAsync(user, password);
        }
    }
    

    This can be called from an IHostedService:

    public class SetupIdentityDataSeeder : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        public SetupIdentityDataSeeder(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
    
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var seeder = scope.ServiceProvider.GetRequiredService();
    
                await seeder.SeedAsync();
            }
        }
    
        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
    

    Startup would look like:

    public void ConfigureServices(IServiceCollection services)
    {
        //...
    
        services.AddHostedService();
    }
    

提交回复
热议问题