文章内容

2019/2/18 20:05:50,作 者: 黄兵

IdentityServer4 Mysql相关问题

最近需要用到IdentityServer认证功能,但是数据库采用的是Mysql,Identityserver4官方的实例采用的是SQLServer。

最近研究了如何使用Mysql持久化IdentityServer4相关数据,以及Identity数据。具体操作步骤如下:


1、修改初始化数据库代码:

setup.cs文件:

private void InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();

var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
if (!context.Clients.Any())
{
foreach (var client in Config.GetClients())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}

if (!context.IdentityResources.Any())
{
foreach (var resource in Config.GetIdentityResources())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}

if (!context.ApiResources.Any())
{
foreach (var resource in Config.GetApiResources())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}

最主要增加了这一句:

serviceScope.ServiceProvider
.GetRequiredService<ApplicationDbContext>()
.Database.Migrate();

之后执行如下如下命令:

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

之后又增加了一个命令:

dotnet ef migrations add InitialIdentityServerApplicationDbMigration -c ApplicationDbContext -o Data/Migrations/IdentityServer/ApplicationDb

这两个命令就初始化了数据库。

下面就是开始生成数据库,具体在Configure()下面增加数据库初始化方式:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
InitializeDatabase(app);

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
}


参考资料:

1、各种坑——IdentityServer4与MySQL

2、Using ASP.NET Core Identity

3、使用Identity Server 4建立Authorization Server (5)


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - IdentityServer4 Mysql相关问题

分享到:

发表评论

评论列表