Search code examples
c#asp.netasp.net-identity

Create default user/admin when website initialize - Identity


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.


Solution

  • 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 = "[email protected]";
        admin.UserName = "[email protected]";
    
        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.