We need to add the role specific services to our application. To do this, we need to update the code in the ConfigureServices
method of the Startup
class.
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
The IdentityRole
type is the default role type provided by ASP.NET Core Identity. But you can provide a different type if it doesn’t fit your requirements.
Next, we’re going to seed our database with some roles – we’re going to add a User and Admin role. To do this we’re going to override the OnModelCreating
method of the ApplicationDbContext
.
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "User", NormalizedName = "USER", Id = Guid.NewGuid().ToString(), ConcurrencyStamp = Guid.NewGuid().ToString() });
builder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN", Id = Guid.NewGuid().ToString(), ConcurrencyStamp = Guid.NewGuid().ToString() });
}
}
Once this is done we need to generate a migration and then apply it to the database.
Add-Migration SeedRoles
Update-Database
Via SQL
INSERT INTO [dbo].[AspNetRoles]
([Id]
,[Name]
,[NormalizedName]
,[ConcurrencyStamp])
VALUES
(NEWID()
,'ProductManager'
,'PRODUCTMANAGER'
,NEWID())
Database Check
SELECT * FROM [dbo].[AspNetUsers]
SELECT * FROM [dbo].[AspNetRoles]
SELECT * FROM [dbo].[AspNetUserRoles]
SELECT
ur.UserId
, ur.RoleId
, u.Email
, r.Name
, r.NormalizedName
FROM
[dbo].[AspNetUserRoles] ur
LEFT JOIN [dbo].[AspNetUsers] u ON u.Id = ur.UserId
LEFT JOIN [dbo].[AspNetRoles] r ON r.Id = ur.RoleId
Comments