July 16th, 2016

ASP.NET Core Identity: Add Roles on Application Startup

In ASP.NET Core application, you want to seed roles and users in the database. This post explains how to add Roles on application startup using ASP.NET Core Identity. It is written in following environment:

ASP.NET Core 1.0.1
Postgresql 9.5.4 database
Npgsql 3.1.9
Dapper 1.50.2
Visual Studio 2015 update 3
Identity.Dapper

Here is Enum for roles:

 public enum Roles
    {
       Administrator,
       Editor,
       User,
       Tester
    }

I am using custom RoleStore and UserStore with Dapper(Identity.Dapper).

1. Create a static class:

  public static class DataInitializer
    {
        public static async Task SeedRoles(IServiceProvider serviceProvider)
        {
                    var roleManager = serviceProvider.GetRequiredService<RoleManager<DapperIdentityRole<int>>>();
                    foreach (var role in Enum.GetNames(typeof(Roles)))
                    {
                        if (!await roleManager.RoleExistsAsync(role))
                        {
                            await roleManager.CreateAsync(new DapperIdentityRole(role));
                        }
                    }            
        }
    }

As in the code Identity is configured in following way:

        services.AddIdentity<DapperIdentityUser, DapperIdentityRole<int>>(x =>
                              {
                                   x.Password.RequireDigit = false;
                                   x.Password.RequiredLength = 1;
                                   x.Password.RequireLowercase = false;
                                   x.Password.RequireNonAlphanumeric = false;
                                   x.Password.RequireUppercase = false;
                               })

So in SeedRoles method, RoleManager service is retrieved keeping same signature:

 var roleManager = serviceProvider.GetRequiredService<RoleManager<DapperIdentityRole<int>>>();

If you are using default Identity configuration i.e. in Startup.cs

   services.AddIdentity<ApplicationUser, IdentityRole>()

Then use RoleManager<IdentityRole> as below:

public static class DataInitializer
{
    public static async Task SeedRoles(IServiceProvider serviceProvider)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        foreach (var role in Enum.GetNames(typeof(Roles)))
        {
            if (!await roleManager.RoleExistsAsync(role))
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
        }
    }
}

2. Now call SeedRoles method in Startup.cs

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
		...
   		DataInitializer.SeedRoles(app.ApplicationServices).Wait();
        }

When you run application, the roles are inserted if not exist in database. Similarly, you can seed users in the database.
Hope It helps. In Next tutorial, we will implement Role based security. Stay tuned and enjoy ASP.NET Core.

  • Henrique Duarte

    Do you know if there’s a change to be done for .Net Core 2.0?
    I’m always getting an error on this line:
    var roleManager = serviceProvider.GetRequiredService<RoleManager>();