我正在尝试使用mysql作为后端数据库来配置Identity server 4,但是在Idserver4的官方网站上找不到任何关于配置的指导教程。
请问mysql是否可以用于此配置?
我正在尝试使用mysql作为后端数据库来配置Identity server 4,但是在Idserver4的官方网站上找不到任何关于配置的指导教程。
请问mysql是否可以用于此配置?
关注 IdentityServer 示例中的 8_AspNetIdentity 示例。
添加 MySql.Data.EntityFrameworkCore NuGet 包。
在开始之前,为防万一,请将迁移应用到 Sql Server。稍后我们会再次回顾这一点。
从更改 Appsettings.json 中的 connectionString 开始。
"DefaultConnection": "server=localhost;userid=root;pwd=rootpassword;persistsecurityinfo=True;port=3306;database=AspIdUsers;sslmode=none;AllowPublicKeyRetrieval=true;"
请注意,您的数据库密码在此处以明文形式呈现,因此如果该文件对更广泛的受众可见,请使用用户机密来提供它。
上下文定义需要一些工作,因为MySql将布尔值持久化为整数,如果未映射,这将导致强制转换异常。在ApplicationDbContext的OnModelCreating方法中添加以下内容:
// Conversions required for "No coercion operator is defined between types 'System.Int16' and 'System.Boolean'."
builder
.Entity<ApplicationUser>()
.Property(u => u.EmailConfirmed).HasConversion<Int16>()
;
builder
.Entity<ApplicationUser>()
.Property(u => u.LockoutEnabled).HasConversion<Int16>()
;
builder
.Entity<ApplicationUser>()
.Property(u => u.PhoneNumberConfirmed).HasConversion<Int16>()
;
builder
.Entity<ApplicationUser>()
.Property(u => u.PhoneNumberConfirmed).HasConversion<Int16>()
;
builder
.Entity<ApplicationUser>()
.Property(u => u.TwoFactorEnabled).HasConversion<Int16>()
;
builder
.Entity<ApplicationUser>()
.Property(u => u.PhoneNumberConfirmed).HasConversion<Int16>()
;
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(connectionString));
更改迁移模块20180109192453_CreateIdentitySchema.Designer和ApplicationDbContextModelSnapshot,以在AspNetUserLogins、AspNetUserRoles、AspNetUserTokens的关键字段上设置最大长度(AspNetUserTokens具有三个部分的键,因此使用长度为200)。
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(256);
b.Property<string>("ProviderKey")
.HasMaxLength(256);
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.HasMaxLength(256)
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
如果你遇到迁移错误提示你的键超出3072限制,注意表格并使用这个示例将其长度缩短。
如果操作迁移变得不可能,从SqlServer导出创建语句并手工制作它们的MySql等效语句。
成功创建数据库后,您需要使用MySql Workbency在AspNetUserClaims的Id列上设置自动增量。
然后你就可以愉快地开始了。
如果你选择Combined_AspId_and_EFStorage,事情会变得更加复杂。你无法访问ConfigurationDbContext和PersistedGrantDbContext。它们是通过Indentity Server 4 nuget包管理的,所以你需要注入自己的版本来解决强制问题。
services.AddDbContext<yourDbContext>(options => options.UseMySql(yourConnectionName, mySqlOptions => mySqlOptions.CommandTimeout(timeout)));