text
stringlengths
0
13.4k
}
The InitializeAsync() method uses an IServiceProvider (the
collection of services that is set up in the Startup.ConfigureServices()
method) to get the RoleManager and UserManager from ASP.NET Core
Identity.
Add two more methods below the InitializeAsync() method. First, the
EnsureRolesAsync() method:
private static async Task EnsureRolesAsync(
RoleManager<IdentityRole> roleManager)
{
var alreadyExists = await roleManager
.RoleExistsAsync(Constants.AdministratorRole);
90
Authorization with roles
if (alreadyExists) return;
await roleManager.CreateAsync(
new IdentityRole(Constants.AdministratorRole));
}
This method checks to see if an Administrator role exists in the
database. If not, it creates one. Instead of repeatedly typing the string
"Administrator" , create a small class called Constants to hold the
value:
Constants.cs
namespace AspNetCoreTodo
{
public static class Constants
{
public const string AdministratorRole = "Administrator";
}
}
If you want, you can update the ManageUsersController to use
this constant value as well.
Next, write the EnsureTestAdminAsync() method:
SeedData.cs
private static async Task EnsureTestAdminAsync(
UserManager<ApplicationUser> userManager)
{
var testAdmin = await userManager.Users
.Where(x => x.UserName == "admin@todo.local")
.SingleOrDefaultAsync();
if (testAdmin != null) return;
testAdmin = new ApplicationUser
{
91
Authorization with roles
UserName = "admin@todo.local",
Email = "admin@todo.local"
};
await userManager.CreateAsync(
testAdmin, "NotSecure123!!");