Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {     protected override void OnModelCreating(ModelBuilder builder)     {         // On event model creating         base.OnModelCreating(builder);     } } 

Please note ApplicationDbContext use IdentityDbContext and not DbContext.

There is any IdentityConfig.cs. Where i need to put the classic protected override void Seed to create role and user if it does not exist?

like image 520
Sauron Avatar asked Dec 17 '15 20:12

Sauron


People also ask

How do you seed a role in identity?

You can seed Users and Roles in OnModelCreating() method inside IdentityDbContext. cs file as shown below. Notice that the keys have to be predefined to avoid seeding new users and roles everytime this method is executed. This is the correct answer for .

How do I seed data in .NET core?

Here is the sample code. After adding this piece of code, we need to build the application. Now, let's open Package Manager Console . We need to run "add-migration user_role" and "update-database" commands in order to reflect seeding changes in database.


2 Answers

My way of doing this is to create a class in models namespace.

public class SampleData {     public static void Initialize(IServiceProvider serviceProvider)     {         var context = serviceProvider.GetService<ApplicationDbContext>();          string[] roles = new string[] { "Owner", "Administrator", "Manager", "Editor", "Buyer", "Business", "Seller", "Subscriber" };          foreach (string role in roles)         {             var roleStore = new RoleStore<IdentityRole>(context);              if (!context.Roles.Any(r => r.Name == role))             {                 roleStore.CreateAsync(new IdentityRole(role));             }         }           var user = new ApplicationUser         {             FirstName = "XXXX",             LastName = "XXXX",             Email = "[email protected]",             NormalizedEmail = "[email protected]",             UserName = "Owner",             NormalizedUserName = "OWNER",             PhoneNumber = "+111111111111",             EmailConfirmed = true,             PhoneNumberConfirmed = true,             SecurityStamp = Guid.NewGuid().ToString("D")         };           if (!context.Users.Any(u => u.UserName == user.UserName))         {             var password = new PasswordHasher<ApplicationUser>();             var hashed = password.HashPassword(user,"secret");             user.PasswordHash = hashed;              var userStore = new UserStore<ApplicationUser>(context);             var result = userStore.CreateAsync(user);          }          AssignRoles(serviceProvider, user.Email, roles);          context.SaveChangesAsync();     }      public static async Task<IdentityResult> AssignRoles(IServiceProvider services, string email, string[] roles)     {         UserManager<ApplicationUser> _userManager = services.GetService<UserManager<ApplicationUser>>();         ApplicationUser user = await _userManager.FindByEmailAsync(email);         var result = await _userManager.AddToRolesAsync(user, roles);          return result;     }  } 

To run this code on startup. In Startup.cs at end of configure method just after route configuration add following code as Stafford Williams said before.

SampleData.Initialize(app.ApplicationServices); 
like image 152
Muhammad Abdullah Avatar answered Sep 18 '22 17:09

Muhammad Abdullah


As of the time of this writing, there is no plug in place for seeding the database, but you can create a class and add it to your container to do the same thing on app start, here is how I've done it, first create a class:

public class YourDbContextSeedData {     private YourDbContext _context;      public YourDbContextSeedData(YourDbContext context)     {         _context = context;     }      public async void SeedAdminUser()     {         var user = new ApplicationUser         {             UserName = "[email protected]",             NormalizedUserName = "[email protected]",             Email = "[email protected]",             NormalizedEmail = "[email protected]",             EmailConfirmed = true,             LockoutEnabled = false,             SecurityStamp = Guid.NewGuid().ToString()         };          var roleStore = new RoleStore<IdentityRole>(_context);          if (!_context.Roles.Any(r => r.Name == "admin"))         {             await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });         }          if (!_context.Users.Any(u => u.UserName == user.UserName))         {             var password = new PasswordHasher<ApplicationUser>();             var hashed = password.HashPassword(user, "password");             user.PasswordHash = hashed;             var userStore = new UserStore<ApplicationUser>(_context);             await userStore.CreateAsync(user);             await userStore.AddToRoleAsync(user, "admin");         }          await _context.SaveChangesAsync();     } 

Register the type in ConfigureServices method of your Startup.cs class:

services.AddTransient<YourDbContextSeedData>(); 

Next pass the YourDbContextSeedData class to the Configure method of your Startup.cs class and use it:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, YourDbContextSeedData seeder) {   seeder.SeedAdminUser(); } 
like image 27
Hamid Mosalla Avatar answered Sep 20 '22 17:09

Hamid Mosalla