Randal Cunanan
Randal Cunanan

Reputation: 2529

Create a default user account using ASP.NET Idenity

I am developing a simple application using ASP.NET MVC 5 and the Identity API. I would like to ask how I am able to create a Super Administrator account inside a Super Administrators role upon creation of the tables and startup of the application. I am using the default ASP.NET MVC 5 with Individual Accounts template of Visual Studio 2013 and I am not sure how to do what I aim.

Upvotes: 3

Views: 11994

Answers (2)

shA.t
shA.t

Reputation: 16968

I do it inside of seed() method of Configuration class like this:

protected override void Seed(AuthContext context)
{
    const string userName = "AdminUserName";
    const string password = "AdminPassword";
    const string roleName = "AdminRole";
    const string phoneNumber = "PhoneNumber";

    var appUserStore = new UserStore<ApplicationUser>(context);
    var appUserManager = new UserManager<ApplicationUser>(appUserStore);
    var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context));

    try
    {
        var user = context.Users.SingleOrDefault(u => u.UserName == userName);
        var role = context.Roles.SingleOrDefault(r => r.Name == roleName);

        if (role == null)
        {
            appRoleManager.CreateAsync(new IdentityRole(roleName)).Wait();
            role = context.Roles.SingleOrDefault(r => r.Name == roleName);
        }
        if (user == null)
        {
            appUserManager.CreateAsync(new ApplicationUser { UserName = userName, PhoneNumber = phoneNumber}, password).Wait();
            user = context.Users.SingleOrDefault(u => u.UserName == nationalCode);
        }

        var userRole = user.Roles.SingleOrDefault(r => r.RoleId == role.Id);

        if (userRole == null)
        {
            appUserManager.AddToRoleAsync(user.Id, roleName).Wait();
        }
    }
    catch (Exception ex)
    {
        // Error catched!
    }
}

Upvotes: 1

Randal Cunanan
Randal Cunanan

Reputation: 2529

Never mind, I found this useful link that shows exactly what I want:

https://github.com/rustd/AspnetIdentitySample/blob/master/AspnetIdentitySample/App_Start/IdentityConfig.cs

Upvotes: 5

Related Questions