Search code examples
asp.netasp.net-coreasp.net-identityasp.net-core-1.0

How to add Admin role ( My solution )


I cannot find any working solution... I tried every google result. I am figthing with this for couple of hours.

So I just insert my new role to SQL tables with:

insert into [dbo].[AspNetRoles] ( [Id]
      ,[ConcurrencyStamp]
      ,[Name]
      ,[NormalizedName] )
values(1,NULL,'Admin','Admin') ;

Insert into [dbo].[AspNetUserRoles] (  [UserId]
      ,[RoleId] )
VALUES('user_id_from_[dbo].[AspNetUsers]' , 1 )

I think it is so ugly and really worst I can do, but it's working.

On SO is one answer marked as solution: Asp.Net core MVC6 How to initially add roles in Identity 3

but I really have no idea after looking for answers in google how to properly initialize roleManager in Startup.cs.

I don't even believe it is really that hard. I think I just missing some clue.


Solution

  • Usually Admin Roles are seeded into the database while creating the schema. You are using Identity to create or seed the Admin Role. Identity uses Code-First approach so that you can customize it as much as possible. Don't use SQL queries manually. Below is way through which you can create an Admin User with Administrator privileges data at runtime using DI because EFCore does not yet support built-in support for Seeding data (It will support in the update).

    To Seed Data, create a class (AdministratorSeedData.cs for example) in the Data Folder and add the following code.

    public class AdministratorSeedData
    {
        private RoleManager<IdentityRole> _roleManager;
        private UserManager<ApplicationUser> _userManager;
    
        public AdministratorSeedData(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }
    
        public async Task EnsureSeedDataAsync()
        {
            if (await _userManager.FindByEmailAsync("[email protected]") == null)
            {
                ApplicationUser administrator = new ApplicationUser()
                {
                    UserName = "[email protected]",
                    Email = "[email protected]"
                };
    
                await _userManager.CreateAsync(administrator, "Passw0rd123!");
                await _roleManager.CreateAsync(new IdentityRole("Administrator"));
    
                IdentityResult result = await _userManager.AddToRoleAsync(administrator, "Administrator");
            }
        }
    }
    

    Then in the Startup.cs class, register this service in the DI container as:

        public void ConfigureServices(IServiceCollection services)
        {
            ....
            services.AddTransient<AdministratorSeedData>();
        }
    

    and

        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AdministratorSeedData seeder)
        {
            ....
            await seeder.EnsureSeedDataAsync();
        }
    

    Make sure that there is no database created. Run the application and you will see that the User with Administrator Role is created successfully.