在Asp.Net Core Identity中使用Code First为AspNetUserTokens表新增列
.NET 5 Web API Code First 扩展 AspNetUserTokens 表实现方案
实现步骤
- 第一步:自定义扩展IdentityUserToken实体
public class ApplicationUserToken : IdentityUserToken<string> { // 可按需调整字段类型,比如用string存储加密算法标识 public int EncryptionVersion { get; set; } }
- 第二步:修改自定义DbContext的继承配置,替换默认UserToken实体
public class ApplicationDbContext : IdentityDbContext< IdentityUser, // 若已自定义User实体则替换为你自己的实现类 IdentityRole, // 若已自定义Role实体则替换为你自己的实现类 string, // 与你项目的Identity主键类型保持一致 IdentityUserClaim<string>, IdentityUserRole<string>, IdentityUserLogin<string>, IdentityRoleClaim<string>, ApplicationUserToken // 替换为自定义的UserToken实现 > { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 显式绑定表名,保持原有AspNetUserTokens表名不变 modelBuilder.Entity<ApplicationUserToken>().ToTable("AspNetUserTokens"); } }
- 第三步:调整Identity服务注册配置,适配自定义UserToken
// Startup.cs ConfigureServices 方法中 services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
- 第四步:生成迁移并更新数据库
在包管理器控制台依次执行以下命令:Add-Migration AddEncryptionVersionToAspNetUserTokensUpdate-Database
如果需要手动执行SQL,也可以从生成的迁移文件中导出对应的SQL脚本执行。
注意事项
- 原有Identity内置的2FA密钥、恢复码的读写逻辑不需要修改,框架会自动适配自定义的UserToken实体
- 若需要操作新增的EncryptionVersion字段,可以直接从ApplicationDbContext中获取
DbSet<ApplicationUserToken>进行读写,也可以扩展UserManager的方法实现封装 - 该方案完全符合EF Core Code First的规范,后续修改字段属性也可以通过迁移完成,不需要手动改表结构
内容的提问来源于stack exchange,提问作者frosty
相关产品推荐
相关产品推荐

