Create default user/admin when website initialize - Identity

不羁的心 提交于 2019-12-19 08:55:00

问题


I'm very noob in asp.net area. So my question maybe got answered anywhere in the internet but neither of them I understand the flow creation. Here is the question.

I'm trying to create simple 'Website project', when this site was up, it should creating all necessary identity table inside database if the table not exist yet. Then I'll add up role to the table and set one user as super admin to this table.

Can anyone help me regarding this or share any link regarding this question.


回答1:


I am assuming you are using ASP.NET MVC.

You can use Database Initialization to seed your database.

public class MyDBInitializer : CreateDatabaseIfNotExists<ApplicationDBContext>
{
    protected override void Seed(ApplicationDBContext context)
    {
        base.Seed(context);
    }
}

On the seed method you can populate your database and create a default user for your application.

protected override void Seed(ApplicationDBContext context)
{
    // Initialize default identity roles
    var store = new RoleStore<IdentityRole>(context);
    var manager = new RoleManager<IdentityRole>(store);               
    // RoleTypes is a class containing constant string values for different roles
    List<IdentityRole> identityRoles = new List<IdentityRole>();
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.Admin });
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.Secretary });
    identityRoles.Add(new IdentityRole() { Name = RoleTypes.User });

    foreach(IdentityRole role in identityRoles)
    {
         manager.Create(role);
    }

    // Initialize default user
    var store = new UserStore<ApplicationUser>(context);
    var manager = new UserManager<ApplicationUser>(store);
    ApplicationUser admin = new ApplicationUser();
    admin.Email = "admin@admin.com";
    admin.UserName = "admin@admin.com";

    manager.Create(admin, "1Admin!");
    manager.AddToRole(admin.Id, RoleTypes.Admin); 

    // Add code to initialize context tables

    base.Seed(context);
}

And on your Global.asax.cs you should register your database initializer

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    Database.SetInitializer(new MyDBInitializer());
}

Note that there are different types of database initialization strategies whose behavior will depend on your database initializer. Do check the link above.



来源:https://stackoverflow.com/questions/39737554/create-default-user-admin-when-website-initialize-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!