配置APS.NET Core 提供的 用户角色的数据库
Authentication :验证用户是否登录
Authorization :验证用户是否对某个资源有访问权限
ASP.NET Core 提供了Identity 身份标识框架,它用户RBAC 基于角色的访问控制策略。内置了对用户(UserManager)、角色(RoleManager)等表的管理接口。
Identity 身份标识框架中提供了 IdentityUser<TKey>、IdentityRole<TKey> 两个实体类型,TKey代表键的类型。我们一般还是需要为实体类增加额外属性,因此我们一般编写继承这两个类的User和Role.
一、定义用户和角色类
用户类:
public class User:IdentityUser<long> { public DateTime CreationTime { get; set; } public string? NickName { get; set; } }
角色类:
public class Role:IdentityRole<long> { }
二、用NuGet 安装 Microsoft.AspNetCore.Identity.EntityFrameworkCore 包
三、定义权限数据库上下文
public class IdDbContext : IdentityDbContext<User, Role, long> { public IdDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } }
UserManager 和 RoleManager 封装了对 IdentityDbContext 的操作,所以无须直接通过DbContext来操作。
四、注册服务并配置 用户和角色
//配置用户角色 builder.Services.AddDbContext<IdDbContext>(options => { string connStr = builder.Configuration.GetConnectionString("DefaultConnection"); options.UseSqlServer(connStr); }); builder.Services.AddDataProtection(); services.AddIdentityCore<User>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; }); var idBuilder = new IdentityBuilder(typeof(User), typeof(Role), services); idBuilder.AddEntityFrameworkStores<IdDbContext>() .AddDefaultTokenProviders() .AddRoleManager<RoleManager<Role>>() .AddUserManager<UserManager<User>>();
五、执行数据库迁移,生成用户角色相关权限表
Add-Migration Update-databse
//项目中有多个DbContext 时,执行迁移需要指出是那个 add-migration add_user_Role -context IdDbContext
六、创建用户名和角色
[Route("api/[controller]")] [ApiController] public class UserRoleController : ControllerBase { private readonly ILogger<UserRoleController> m_logger; private readonly UserManager<User> m_userManager; private readonly RoleManager<Role> m_roleManager; public UserRoleController(ILogger<UserRoleController> logger, UserManager<User> userManager, RoleManager<Role> roleManager) { m_logger = logger; m_userManager = userManager; m_roleManager = roleManager; } [HttpPost] public async Task<ActionResult> CreateUserRole() { bool roleExists = await m_roleManager.RoleExistsAsync("admin"); if (!roleExists) { Role role = new Role { Name = "Admin" }; var r = await m_roleManager.CreateAsync(role); if (!r.Succeeded) { return BadRequest(r.Errors); } } User user = await m_userManager.FindByNameAsync("yyy"); if (user == null) { user = new User { UserName = "yyy", Email = "flyingdream8@163.com", EmailConfirmed = true }; var r = await m_userManager.CreateAsync(user, "123456"); if (!r.Succeeded) { return BadRequest(r.Errors); } r = await m_userManager.AddToRoleAsync(user, "admin"); if (!r.Succeeded) { return BadRequest(r.Errors); } } return Ok(); } }