
How To Seed Users And Roles With Code In ASP.NET Core Identity
With the help of ASP.NET Core identity, you can implement authentication and authorization for your web applications. Working with ASP.NET Core Identity, sometimes you have to create a default user accounts and roles in the system. In ASP.NET MVC it can be done in Global.asax and Application_Start event handler. In ASP.NET Core the process different because its application startup process is different.
In case you there is a MyIdentityDbContext, MyIdentityUser and MyIdentityRole classes ready, next your aim is to create a few user accounts and some roles when the application executes for the first time. This is to be done only when those users and roles don’t exist in the database.
Here we shall discuss two ways of putting the data:
- Using Configure () method
- Using Main () method
The former method is simple and direct with minimal coding, as you inject objects in other parts of your application, you can inject them into the Configure () method also. The latter approach is complex and needs you to shift the seeding operation to the Main() from Program.cs.
Edit your Configure () method signature as shown below :
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
UserManager<MyIdentityUser> userManager,
RoleManager<MyIdentityRole> roleManager)
{
…
…
}
Next can be inserted UserManager and RoleManager into the Configure() method. Hence you can use UserManager to develop user accounts and RoleManager to create roles at the application startup. Instead of directly writing codes inside the Configure() method, it would be isolated in a separate class and then get it from there.
What is necessary is to add a new class called MyIdentityDataInitializer into the project. The following code shows the structure of this class :
public static class MyIdentityDataInitializer
{
public static void SeedData
(UserManager<MyIdentityUser> userManager,
RoleManager<MyIdentityRole> roleManager)
{
}
public static void SeedUsers
(UserManager<MyIdentityUser> userManager)
{
}
public static void SeedRoles
(RoleManager<MyIdentityRole> roleManager)
{
}
}
The MyIdentityDataInitializer class has 3 static methods – SeedRoles(), SeedUsers() and SeedData(). If you want to create both – users and roles – then you would summon SeedData().
Here we shall take a look at the codes that go inside the methods.
The SeedRoles() develops desired default roles in the system and appears like this :
public static void seed rolls
(RoleManager<MyIdentityRole> roleManager)
{
if (!roleManager.RoleExistsAsync
(“NormalUser”).Result)
{
MyIdentityRole role = new MyIdentityRole();
role.Name = “NormalUser”;
role.Description = “Perform normal operations.”;
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
if (!roleManager.RoleExistsAsync
(“Administrator”).Result)
{
MyIdentityRole role = new MyIdentityRole();
role.Name = “Administrator”;
role.Description = “Perform all the operations.”;
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
}
The SeedRoles() method takes in RoleManager as its parameter. Inside, is created two roles in the system – NormalUser and Administrator. You must change the role names and their description as you need.
The SeedUsers() develops desired default user accounts and appears like this :
public static void SeedUsers
(UserManager<MyIdentityUser> userManager)
{
if (userManager.FindByNameAsync
(“user1”).Result == null)
{
MyIdentityUser user = new MyIdentityUser();
user.UserName = “user1”;
user.Email = “user1@localhost”;
user.FullName = “Nancy Davolio”;
user.BirthDate = new DateTime(1960, 1, 1);
IdentityResult result = userManager.CreateAsync
(user, “password_goes_here”).Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user,
“NormalUser”).Wait();
}
}
if (userManager.FindByNameAsync
(“user2”).Result == null)
{
MyIdentityUser user = new MyIdentityUser();
user.UserName = “user2”;
user.Email = “user2@localhost”;
user.FullName = “Mark Smith”;
user.BirthDate = new DateTime(1965, 1, 1);
IdentityResult result = userManager.CreateAsync
(user, “password_goes_here”).Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user,
“Administrator”).Wait();
}
}
}
The SeedUsers() method accepts a UserManager and develops two users – user1 and user2. It has to be first checked if a user with the same name exists or not. If it doesn’t exist then it has to be created with default values of l, full name, and birth date. The values can be changed as needed.
The SeedUsers() and SeedRoles() do not return any value. But the signature can be changed to return some status of success or failure if you so wish.
The SeedData() basically summons SeedRoles() and SeedUsers() and appears like this :
public static void SeedData
(UserManager<MyIdentityUser> userManager,
RoleManager<MyIdentityRole> roleManager)
{
SeedRoles(roleManager);
SeedUsers(userManager);
}
The SeedData() method accepts a UserManager and a RoleManager. Inside, it summons SeedRoles() and SeedUsers(). Watch out that, SeedRoles() is summoned first because SeedUsers() assigns certain roles to the users being added and those roles must exist in the system before adding the users.
Seeding data in Configure()
And it is time to use the MyIdentityDataInitializer class. Open the Startup class, go to Configure() method and add the following line of code:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
UserManager<MyIdentityUser> userManager,
RoleManager<MyIdentityRole> roleManager)
{
…
app.UseAuthentication();
MyIdentityDataInitializer.SeedData(userManager, roleManager);
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: “default”,
template: “{controller=Home}/{action=Index}/{id?}”);
});
}
After summoning, UseAuthentication() we summon SeedData() on MyIdentityDataInitializer.
Execute the application and see if the users get created in the database or not.
In the previous code are created default users and roles in the Configure() method. You can also do that work in Main() method. The following code shows how the Main() code would look like :
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
try
{
var userManager = serviceProvider.
GetRequiredService<UserManager<MyIdentityUser>>();
var roleManager = serviceProvider.
GetRequiredService<RoleManager<MyIdentityRole>>();
MyIdentityDataInitializer.SeedData
(userManager, roleManager);
}
catch
{
}
}
host.Run();
}
Instead of inserting UserManager and RoleManager into Configure() you take them from GetRequiredService() method. The userManager and roleManager objects are next passed on to SeedData() as earlier.
That’s it for now!
If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various best institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.
Happy Coding!
Codes: Google database