Categories
ASP.Net Core Identity

ASP.Net Core Seed User and Role

Data seeding for Identity user tables are different. Here is an example code how to seed data without extending the Identity User table. First step to create a class in Data folder Name it “ApplicationDbInitializer.cs”, following code will be in this class.

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppName.Data
{
    public class ApplicationDbInitializer
    {
        public static void SeedUsers(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            string admin = "Admin";
            string normalUser = "NormalUser";
            string password = "p@55w0rD"; 

            if (roleManager.FindByNameAsync("Admin").Result == null)
            {
                IdentityRole role = new IdentityRole
                {
                    Name = admin,
                    NormalizedName = "ADMIN"
                };

                roleManager.CreateAsync(role).Wait();
            }

            if (roleManager.FindByNameAsync("NormalUser").Result == null)
            {
                IdentityRole role1 = new IdentityRole
                {
                    Name = normalUser,
                    NormalizedName = "NORMALUSER"
                };

                roleManager.CreateAsync(role1).Wait();                
            }

            if (userManager.FindByEmailAsync("admin@domain.com").Result == null)
            {
                IdentityUser user = new IdentityUser
                {
                    UserName = "admin@domain.com",
                    Email = "admin@domain.com"
                };

                IdentityResult result = userManager.CreateAsync(user, password).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, admin).Wait();
                }
            }
        }
    }
}

Second step, call above class from Startup.cs file Configure method. Add this line at bottom of the Configure method.

ApplicationDbInitializer.SeedUsers(userManager, roleManager);

Add dependency injection in Configure method arguments like the code below

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)

Add these two string “UserManager userManager, RoleManager roleManager” in Configure method argument.

In the Startup.cs file need to update ConfigureServices method, create a new service for Identity. Add the following code in ConfigureServices method –

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<AppDbContext>();

Once you run the application, it should create a user, role and assign the user in role in Identity User table.

Happy Coding 🙂