在Asp.Net核心标识中首先使用代码向AspNetUserTokens添加列



我需要添加一列来跟踪存储在现有.Net5 web api应用程序的AspNetUserTokens表中的2FA密钥和恢复代码的加密版本。我可以直接使用Sql命令来进行迁移。如果可能的话,我想使用代码优先的方法。这似乎不属于现有的AspNetUsers&文档中定义的AspNetRoles。如有任何建议,我们将不胜感激。

EF核心代码优先方法允许您向IdentityToUserTokens添加自定义列。一些代码更改将为您完成此任务。

创建继承自IdentityUserToken<TKey>的新类

public class ApplicationUserToken : IdentityUserToken<string>
{
public int CustomColumn { get; set; }
}

将DbContext更改为以下

public class ApplicationContext : IdentityDbContext<
IdentityUser, IdentityRole, string,
IdentityUserClaim<string>,
IdentityUserRole<string>,
IdentityUserLogin<string>,
IdentityRoleClaim<string>,
ApplicationUserToken> //Class inherited by IdentityUserToken<TKey>
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{
}
}

更改后的迁移

public partial class Withcustomtokens : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "CustomColumn",
table: "AspNetUserTokens",
type: "int",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CustomColumn",
table: "AspNetUserTokens");
}
}

有关.net核心身份定制的详细信息,请参阅:身份模型定制

最新更新