In this tutorial, I shall describe the steps you need to follow if you want seed both users and roles data. We will also look at how you can go about securing an ASP.NET Razor Pages application by user and by roles. To keep things simple, we will use the SQLite database.
To proceed with this tutorial, you need to have the following prerequisites:
- VS Code
- You have installed .NET 8.0
Getting Started
In a terminal window, execute the following command to create an ASP.NET Razor Pages application that supports database authentication using the lightweight SQLite database:
dotnet new razor --auth individual -f net8.0 -o SeedIdentity
Change directory to the newly created folder then run the application:
cd SeedIdentity
dotnet watch
Click on the Register link on the top-right side of your keyboard to add a new user.
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => {options.Stores.MaxLengthForKeys = 128;}).AddEntityFrameworkStores<ApplicationDbContext>().AddRoles<IdentityRole>().AddDefaultUI().AddDefaultTokenProviders();
using (var scope = app.Services.CreateScope()) {var services = scope.ServiceProvider;var context = services.GetRequiredService<ApplicationDbContext>();context.Database.Migrate();var userMgr = services.GetRequiredService<UserManager<IdentityUser>>();var roleMgr = services.GetRequiredService<RoleManager<IdentityRole>>();IdentitySeedData.Initialize(context, userMgr, roleMgr).Wait();}
- Instances of ApplicationDbContext, UserManager<IdentityUser> & RoleManager<IdentityRole> are obtained
- If there are any outstanding migrations, they are automatically executed
- The IdentitySeedData.Initialize() method is called
To prove that user and role data are successfully seeded, login with one of the below credentials that were previously seeded:
Password | Role | |
---|---|---|
aa@aa.aa | P@$$w0rd | Admin |
mm@mm.mm | P@$$w0rd | Member |
No comments:
Post a Comment