ASP.NET Core Identity是一个会员身份系统,早期它的名字是Membership,当然那是一段“古老”的历史,现在我们来了解全新的Identity。它允许我们创建、读取、更新和删除账户。支持账号验证、身份验证、授权、恢复密码和SMS双因子身份验证。它还支持微软、Facebook和Google等第三方登录提供商。它提供了一个丰富的API,并且这些API还可以进行大量的扩展。
Identity 支持跨数据库
下面开始 asp.net core 实战配置。所有代码 都是 使用 .net6 如有其他版本 笔者会 标明清楚
1.首先 创建 MyUser.cs 文件
using Microsoft.AspNetCore.Identity;
namespace aspnetcore013
{
public class MyUser:IdentityUser<long>//long是主键的类型
{
//这里是 自定义的自增 字段 会创建到 数据库中 AspNetUsers表中
public string? WeChat { get; set; }
}
}
2. 创建 MyRole.cs 文件
using Microsoft.AspNetCore.Identity;
namespace aspnetcore013
{
public class MyRole:IdentityRole<long>//long是主键的类型
{
}
}
3. 创建 MyDBcontext.cs 文件 这里要注意 IdentityDbContext<MyUser,MyRole,long> 设置相关联
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace aspnetcore013
{
public class MyDBcontext:IdentityDbContext<MyUser,MyRole,long>
{
public MyDBcontext(DbContextOptions<MyDBcontext> options)
: base(options)
{
}
}
}
4. 在 Program.cs 中 如下 配置
builder.Services.AddDbContext<MyDBcontext>(opt =>
{
opt.UseSqlServer("Data Source=ADMIN\\MSSQLSERVER2012A;Initial Catalog=demo10;User ID=sa;Password=123456");
});
builder.Services.AddDataProtection();
builder.Services.AddIdentityCore<MyUser>(opt =>
{
//自定义的配置
opt.Password.RequireDigit = false;
opt.Password.RequiredLength = 6;
opt.Password.RequireLowercase = false;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
});
IdentityBuilder identityBuilder = new IdentityBuilder(typeof(MyUser),typeof(MyRole),builder.Services);
identityBuilder.AddEntityFrameworkStores<MyDBcontext>().AddDefaultTokenProviders()
.AddUserManager<UserManager<MyUser>>().AddRoleManager<RoleManager<MyRole>>();
5.开始 做迁移 Add-migration 和 updade-database
使用的 nuget包 如下
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools