text
stringlengths
0
13.4k
<td>Email</td>
</tr>
</thead>
@foreach (var user in Model.Everyone)
88
Authorization with roles
{
<tr>
<td>@user.Id</td>
<td>@user.Email</td>
</tr>
}
</table>
Start up the application and try to access the /ManageUsers route while
logged in as a normal user. You'll see this access denied page:
That's because users aren't assigned the Administrator role
automatically.
Create a test administrator account
For obvious security reasons, it isn't possible for anyone to register a
new administrator account themselves. In fact, the Administrator role
doesn't even exist in the database yet!
You can add the Administrator role plus a test administrator account to
the database the first time the application starts up. Adding first-time
data to the database is called initializing or seeding the database.
Create a new class in the root of the project called SeedData :
89
Authorization with roles
SeedData.cs
using System;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCoreTodo
{
public static class SeedData
{
public static async Task InitializeAsync(
IServiceProvider services)
{
var roleManager = services
.GetRequiredService<RoleManager<IdentityRole>>();
await EnsureRolesAsync(roleManager);
var userManager = services
.GetRequiredService<UserManager<ApplicationUser>>(
);
await EnsureTestAdminAsync(userManager);
}
}