在MVC 5中使用密码播种管理员角色?

时间:2015-04-27 00:05:29

标签: entity-framework asp.net-mvc-5 seed asp.net-roles

我正在尝试使用Entity Framework在MVC5中播放管理员角色,似乎我们不再使用WebSecurity和SimpleRoleProvider。

我发现了一篇名为MVC5 Seed Roles and Users的精彩帖子。

我仔细阅读并尝试实施它,但我在两个方面遇到了麻烦。在提供的示例中,他们仅显示如何添加用户名,而网站需要电子邮件密码才能注册。

enter image description here

以下是我以前在MVC4中的表现:

protected override void Seed(PhotoAlbum.Models.UsersContext context)
{
    seedUserAccounts();
}

private void seedUserAccounts()
{
    WebSecurity.InitializeDatabaseConnection("UsersContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);

    SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;

    if (!roles.RoleExists("admin"))
    {
        roles.CreateRole("admin");
    }

    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

    if (membership.GetUser("account", false) == null)
    {
        membership.CreateUserAndAccount("account", "pass");
    }

    if (!roles.IsUserInRole("account", "admin"))
    {
        roles.AddUsersToRoles(new[] { "account" }, new[] { "admin" });
    }
 }

我的问题:

我想知道如何更改以下方法以允许使用电子邮件地址和密码。

   protected override void Seed(BlogEngine.Models.ApplicationDbContext context)
   {

       if (!context.Roles.Any(r => r.Name == "Admin"))
       {
           var store = new RoleStore<IdentityRole>(context);
           var manager = new RoleManager<IdentityRole>(store);
           var role = new IdentityRole { Name = "Admin" };


           manager.Create(role);
       }

       if (!context.Users.Any(u => u.UserName == "myUsername"))
       {
           var store = new UserStore<ApplicationUser>(context);
           var manager = new UserManager<ApplicationUser>(store);
           var user = new ApplicationUser { UserName = "myUsername" };

           manager.Create(user, "ChangeItAsap!");
           manager.AddToRole(user.Id, "Admin");
        }
    }

1 个答案:

答案 0 :(得分:1)

正如史蒂夫格林上面所说的那样,我已经在那里......我确实做了一些改变。这是我的最终解决方案:

  // makes an admin role if one doesn't exist
  if (!context.Roles.Any(r => r.Name == "Admin"))
  {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "Admin" };


        manager.Create(role);
   }
   // if user doesn't exist, create one and add it to the admin role
   if (!context.Users.Any(u => u.UserName == "admin"))
   {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "me@me.com", Email = me@me.com" };

        manager.Create(user, "password");
        manager.AddToRole(user.Id, "Admin");
    }