使用MySql对IdentityServer4进行持久化
哈喽大家好,看见网上很少有使用MySql进行持久化的,毕竟又很多坑,说句实话,就连 MySql.Data.EntityFrameworkCore 都有问题,不知道是.net core更新太快还是其它的问题,但毕竟mssql驱动是没问题的,感觉还是私心太大了。不得以之下选择了一个第三方的驱动 Pomelo.EntityFrameworkCore.MySql 驱动,在这里主要是你安装了它,你就又了它的设计器,但你还需要你安装EFCore的设计器,因为你执行dotnet命令迁移的时候还得靠它,好吧,我们继续,在你的应用程序中最好保持这几个包。能多不能少。
<ItemGroup>
<PackageReference Include="IdentityServer4" Version="2.0.0-rc1" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="2.0.0-rc1" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="2.0.0-rc1" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10062" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
</ItemGroup>
就这样,在Model里创建两个类,一个是用户、一个是关系,这个是Identity的类。其实这个和IdentityServer是没有多大关系的。主要是为了扩展一些东西,比如你需要其它的字段?
public class ApplicationRole : IdentityRole{}
public class ApplicationUser : IdentityUser{}
随后我们定义IdentityDbContext,将我们自己定义的两个类放进去,它是个泛型的。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
} protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
再之后我们就可以注入到.Net Core的服务里了,IdentityServer的数据库中有三个大类,有AspNet的票据用户、资源的管理、以及一些操作的记录。这里你可以用一个database,你也可以分开。
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); services.AddMvc(); string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
sql => sql.MigrationsAssembly(migrationsAssembly)); // this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = ;
});
}
随后注册IdentityServer服务,这个里面调用了 InitializeDatabase 方法为了初始化的迁移数据。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
InitializeDatabase(app); if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");
app.UseIdentityServer();
}
这个方法就很有意思了,获取了.net core的服务实例,然后对我的Context进行了更新迁移,直接将Config中的内存数据添加到了数据库中。
private void InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().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();
}
}
最后你需要执行三个命令,执行EFCore的数据迁移。
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
就这样,生成完毕我们测试一下程序。

Ok,一些正常。
使用MySql对IdentityServer4进行持久化的更多相关文章
- 认证授权:IdentityServer4 - 数据持久化
前言: 前面的文章中IdentityServer4 配置内容都存储到内存中,本篇文章开始把配置信息存储到数据库中:本篇文章继续基于github的代码来实现配置数据持久化到MySQL中 一.基于EFCo ...
- IdentityServer4之持久化很顺手的事
前言 原计划打算在春节期间多分享几篇技术文章的,但到最后一篇也没出,偷懒了吗?算是吧,过程是这样的:每次拿出电脑,在孩姥姥家的院子总有阳光沐浴,看不清屏幕,回屋又有点冷(在强行找理由),于是又带着娃遛 ...
- IdentityServer4.FreeSql 持久化实现
前言 故事是这样开始的: 然后突然又来了句... 扪心自问自从不知道怎么当了 FreeSql 开发群 () 的管理以来, 几乎没有给 FreeSql 做过什么贡献...惭愧惭愧. 借此机会, 似乎可以 ...
- [转]MySQL 5.6 全局事务 ID(GTID)实现原理(三)
原文连接:http://qing.blog.sina.com.cn/1757661907/68c3cad333002s5l.html 原文作者:淘长源 转载注明以上信息 这是 MySQL 5.6 全局 ...
- .NET Core+MySql+Nginx 容器化部署
.NET Core容器化@Docker .NET Core容器化之多容器应用部署@Docker-Compose .NET Core+MySql+Nginx 容器化部署 GitHub-Demo:Dock ...
- mysql+ssl主从复制
一.作为主服务器Master, 会把自己的每一次改动都记录到 二进制日志 Binarylog 中. (从服务器I/O thread会负责来读取master binary log, 然后写入自身rela ...
- Kafka实战-数据持久化
1.概述 经过前面Kafka实战系列的学习,我们通过学习<Kafka实战-入门>了解Kafka的应用场景和基本原理,<Kafka实战-Kafka Cluster>一文给大家分享 ...
- Redis 持久化操作
hash类型 类比:mysql数据库存储数据 持久化操作 以本身的数据以文件形式保存到硬盘中 手动快照持久化 i 备份机制(频率) vi redis.conf save 900 1 900s如果一个 ...
- NET Core+MySql+Nginx
NET Core+MySql+Nginx 容器化部署 .NET Core容器化@Docker.NET Core容器化之多容器应用部署@Docker-Compose.NET Core+MySql+Ngi ...
随机推荐
- [LC] 81. Search in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...
- Android开发之《安全防护》
逆向 java混淆 so加固 网络传输安全
- mvn相关介绍和命令
1.前言 Maven,发音是[`meivin],"专家"的意思.它是一个很好的项目管理工具,很早就进入了我的必备工具行列,但是这次为了把project1项目完全迁移并应用maven ...
- 将tomcat注册成windows系统服务方法
注册服务 打开cmd,进入到[部署tomcat的根目录]Tomcat7.0.65_1/bin,输入 service.bat install 服务名 修改服务名称 比如我注册的 service.ba ...
- iText 中文无法显示
/** * 导出PDF工具com.lowagie.itext测试 * * @param response * @throws IOException * @throws DocumentExcepti ...
- Nginx笔记总结九:Nginx日志配置
ngx_http_log_module用来定义请求日志格式1. access_log指令 语法: access_log path [format [buffer=size [flush=time] ...
- Dcoker跨主机容器通信之overlay
同样是两台服务器: 准备工作: 设置容器的主机名 consul:kv类型的存储数据库(key:value) docker01.02上: vim /etc/docker/daemon.json { &q ...
- <JZOJ4726>种花
挺有意思的贪心 神奇的贪心 #include<cstdio> #include<iostream> #include<cstring> #include<al ...
- 使用document.domain+iframe跨域实例
首先我们假设主页面地址为:http://www.js8.in/mywork/crossdomain/index.html,我们要加载的内容是位于work.2fool.cn域名下的helloworld. ...
- Readings
1984 ([英] 乔治·奥威尔) 这书看完我觉得这根本就是一本恐怖小说,当里面的内容正在和将要发生的时候你就不会觉得里面的描述有点搞笑了.不过看到后面有译者的补充内容说和其他国家的朋友讨论的时候, ...