Users and roles of seeds MVC 5

I played with the new MVC 5, I have several models, setting up the controller and views using the first code migrations.

My question is, how can I sow users and roles? I am currently using some reference data in the Seed method in Configuration.cs. But it seems to me that user and role tables are not created until something first gets to the AccountController.

I currently have two connection strings, so I can separate my data from my authentication in different databases.

How can I populate user tables, roles, etc. along with my others? And not when I got to the account controller?

+88
asp.net-mvc asp.net-mvc-5 ef-migrations
Oct 09 '13 at 19:08
source share
7 answers

Here is an example of a typical Seed approach:

protected override void Seed(SecurityModule.DataContexts.IdentityDb context) { if (!context.Roles.Any(r => r.Name == "AppAdmin")) { var store = new RoleStore<IdentityRole>(context); var manager = new RoleManager<IdentityRole>(store); var role = new IdentityRole { Name = "AppAdmin" }; manager.Create(role); } if (!context.Users.Any(u => u.UserName == "founder")) { var store = new UserStore<ApplicationUser>(context); var manager = new UserManager<ApplicationUser>(store); var user = new ApplicationUser {UserName = "founder"}; manager.Create(user, "ChangeItAsap!"); manager.AddToRole(user.Id, "AppAdmin"); } } 

I used the package manager "update-database". DB and all tables were created and seeded with data.

+172
Dec 11 '13 at 14:18
source share

This is a small addition, but for anyone with "UserId not found." message when trying to sow: (Tom Regan had this question in the comments, and I got stuck on it myself for a while)

This means that manager.Create (user, "ChangeItAsap!") Was not successful. This may have a different reason, but for me it was because my password did not succeed in verifying it.

I had a user password validator that was not called when seeding the database, so the verification rules I used (minlength 4 instead of default 6) were not applied. Make sure your password (and all other fields, for that matter) is verified.

+15
Jun 11 '15 at 19:36
source share

This is my methodological base for Valin's answer, I added roles in db and added a password for the user. This code is placed in the Seed() method in Migrations> Configurations.cs.

 // role (Const.getRoles() return string[] whit all roles) var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); for (int i = 0; i < Const.getRoles().Length; i++) { if (RoleManager.RoleExists(Const.getRoles()[i]) == false) { RoleManager.Create(new IdentityRole(Const.getRoles()[i])); } } // user var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var PasswordHash = new PasswordHasher(); if (!context.Users.Any(u => u.UserName == "admin@admin.net")) { var user = new ApplicationUser { UserName = "admin@admin.net", Email = "admin@admin.net", PasswordHash = PasswordHash.HashPassword("123456") }; UserManager.Create(user); UserManager.AddToRole(user.Id, Const.getRoles()[0]); } 
+13
Jul 06 '15 at 11:54
source share

Here I have a very simple, clean and smooth solution.

  protected override void Seed(UserContext context) { //Step 1 Create the user. var passwordHasher = new PasswordHasher(); var user = new IdentityUser("Administrator"); user.PasswordHash = passwordHasher.HashPassword("Admin12345"); user.SecurityStamp = Guid.NewGuid().ToString(); //Step 2 Create and add the new Role. var roleToChoose = new IdentityRole("Admin"); context.Roles.Add(roleToChoose); //Step 3 Create a role for a user var role = new IdentityUserRole(); role.RoleId = roleToChoose.Id; role.UserId = user.Id; //Step 4 Add the role row and add the user to DB) user.Roles.Add(role); context.Users.Add(user); } 
+5
04 Oct '17 at 10:53 on
source share

What I am doing is creating another asynchronous ideal and calling it synchronously works fine for me.

 protected override void Seed(ApplicationDbContext context) { Task.Run(async () => { await SeedAsync(context); }).Wait(); } private async Task SeedAsync(ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context)); var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole, int, ApplicationUserRole>(context)); if (!roleManager.Roles.Any()) { await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AdminRoleName }); await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AffiliateRoleName }); } if (!userManager.Users.Any(u => u.UserName == "shimmy")) { var user = new ApplicationUser { UserName = "shimmy", Email = "shimmy@gmail.com", EmailConfirmed = true, PhoneNumber = "0123456789", PhoneNumberConfirmed = true }; await userManager.CreateAsync(user, "****"); await userManager.AddToRoleAsync(user.Id, ApplicationRole.AdminRoleName); } } 
+3
Nov 01 '15 at 6:55
source share

It looks like they are changing the authentication method in MVC5, have changed my Global.asax.cs to the next trick!

 using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Threading.Tasks; using MvcAuth.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using System.Threading; using Microsoft.AspNet.Identity.EntityFramework; namespace MvcAuth { public class MvcApplication : System.Web.HttpApplication { async Task<bool> AddRoleAndUser() { AuthenticationIdentityManager IdentityManager = new AuthenticationIdentityManager( new IdentityStore(new ApplicationDbContext())); var role = new Role("Role1"); IdentityResult result = await IdentityManager.Roles.CreateRoleAsync(role, CancellationToken.None); if (result.Success == false) return false; var user = new ApplicationUser() { UserName = "user1" }; result = await IdentityManager.Users.CreateLocalUserAsync(user, "Password1"); if (result.Success == false) return false; result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, role.Id, CancellationToken.None); return result.Success; } protected async void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); bool x = await AddRoleAndUser(); } } } 
+2
Oct 09 '13 at 21:47
source share

write this code in your migration configuration.

Note: Use ApplicationDbContext in the configuration class.

  internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = false; } protected override void Seed(ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. context.Roles.AddOrUpdate(p => p.Name, new IdentityRole { Name = "Admins", Id = "1"}, new IdentityRole { Name = "PowerUsers", Id = "2" }, new IdentityRole { Name = "Users", Id = "3" }, new IdentityRole { Name = "Anonymous", Id = "4" } ); } } 
0
Apr 12 '19 at 12:01
source share



All Articles