最近做一个小项目,实在不想在用户鉴权与授权上重复造轮子,本着“拿来主义”的想法,因为不想在创建工程的时候被“HTTPS”,所以想去集成一下微软自带的Identity组件,在网上找了很多资料,都是.net core 2.X的集成方式,踩了不少坑,也从2.X中汲取了不少经验,特此立贴,以记录学习过程。以下为集成步骤:
1.Nuget引包
Microsoft.AspNetCore.Identity.EntityFrameworkCore【核心组件】
Microsoft.EntityFrameworkCore.SqlServer【数据库交互组件(SQLServer)】
Microsoft.EntityFrameworkCore.Tools【EF数据库交互组件】
建议按上述引用顺序进行引用,可能会引发意外错误
2.建立Context和UserModel
建立两个类文件,分别是IdentityUserContext,AppUser。需要注意的是IdentityUserContext必须继承IdentityDbContext,AppUser必须继承IdentityUser,IdentityUserContext实际上是EF中DBContext的实现,用于交互数据库
代码如下:
using ManagerCore.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace ManagerCore.Context
{
public class IdentityUserContext : IdentityDbContext<AppUser>
{
public IdentityUserContext(DbContextOptions options) : base(options)
{
}
}
}
using Microsoft.AspNetCore.Identity;
namespace Identity.Models
{
public class AppUser : IdentityUser
{
/// <summary>
/// 登录账号
/// </summary>
public string LoginName { get; set; }
/// <summary>
/// 真实姓名
/// </summary>
public string RealName { get; set; }
}
}
3.Startup中做组件配置,直接上代码
第一步,添加鉴权配置
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IdentityUserContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<AppUser, IdentityRole>() // AppUser就是你那个实体类 IdentityRole是Identity默认的
.AddEntityFrameworkStores<IdentityUserContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOpt