Seed ASP.NET Core 1.1 database with a default super-user

831 views Asked by At

I'm starting a new ASP.NET Core MVC project using Identity for authentication. I'd like to add a default super-user to the asp database, so it could add new users then, but i don't know how to do that.

First, i don't know if it is a good idea to use the same database for User's authentication/authorisation and for the rest of the application, or if i should use different databases.

Second, i need to know how to seed the "asp database" with a default super-user.

Following this solution from StackOverflow i know how to access the database, but i'd like to also be abble to get a "userManager" instance to add the super-user to the database using the manager in place of the context.

I have this code at the Startup class:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();
        app.UseIdentity();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        Seed(app);
    }

    public void Seed(IApplicationBuilder app)
    {
        using (var context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>())
        {
            //... perform other seed operations
        }
    }
1

There are 1 answers

0
MorgoZ On

Ok, here is how i have implemented it to add an Admin user. I'm using claims based authorization.

Create a Initializer class:

public interface IDbInitializer
{
    void Initialize();
}

(...)

 public class DbInitializer : IDbInitializer
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public DbInitializer(
        ApplicationDbContext context,
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager)
    {
        _context = context;
        _userManager = userManager;
        _roleManager = roleManager;
    }

    //This example just creates an Administrator role and one Admin users
    public async void Initialize()
    {
        //create database schema if none exists
        _context.Database.EnsureCreated();

        //Create the default Admin account
        string password = "password";
        ApplicationUser user = new ApplicationUser {
            UserName = "Admin",
            Email = "[email protected]",
            EmailConfirmed = true               
        };            
        user.Claims.Add(new IdentityUserClaim<string> { ClaimType = ClaimTypes.Role, ClaimValue = "Admin" });
        var result = await _userManager.CreateAsync(user, password);            
    }
}

And at the startup.cs, add this service at ConfigureService method:

services.AddScoped<IDbInitializer, DbInitializer>();

And finally, change the Configure method like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbInitializer dbInitializer)

and add in it the call to the Initialize method:

  dbInitializer.Initialize();

The DI will take care of the rest.

Here is the full code that i took as reference. It uses Role base authorization: https://gist.github.com/mombrea/9a49716841254ab1d2dabd49144ec092