前言:

  前面的文章中IdentityServer4 配置内容都存储到内存中,本篇文章开始把配置信息存储到数据库中;本篇文章继续基于github的代码来实现配置数据持久化到MySQL中

一、基于EFCore持久化IdentityServer数据

 1、数据库上下文(DbContext )

   在前面使用IDS4时,配置的一些基础:如Api资源、客户端等数据;以及在使用过程中授权后发放的token、授权、授权码等操作数据。如果持久化如何处理呢?IDS4已经提供了对应的方式

    • ConfigurationDbContext

      主要负责数据库对客户端、标识资源、Api资源和CORS等的配置存储

    • PersistedGrantDbContext 

      主要存储操作数据,如:授权码、访问令牌、刷新令牌等相关操作数据

 2、在cz.IdentityServer中添加Nuget包:IdentityServer4.EntityFramework以及EF相关包

Install-Package IdentityServer4.EntityFramework
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Pomelo.EntityFrameworkCore.MySql 

 3、修改Startup文件中ConfigureServices方法中IdentityServer4配置内容如下:

public class Startup
{ private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
} // This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(); services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
     //获取连接串
string connString = _configuration.GetConnectionString("Default");
     string migrationsAssembly = Assembly.GetEntryAssembly().GetName().Name;
//添加IdentityServer服务
services.AddIdentityServer()
//添加这配置数据(客户端、资源)
.AddConfigurationStore(opt =>
{
opt.ConfigureDbContext = c =>
{
c.UseMySql(connString, sql => sql.MigrationsAssembly(migrationsAssembly));
};
})
//添加操作数据(codes、tokens、consents)
.AddOperationalStore(opt =>
{
opt.ConfigureDbContext = c =>
{
c.UseMySql(connString, sql => sql.MigrationsAssembly(migrationsAssembly));
};
//token自动清理
opt.EnableTokenCleanup = true;
////token自动清理间隔:默认1H
//opt.TokenCleanupInterval=3600;
////token自动清理每次数量
//opt.TokenCleanupBatchSize = 100;
})
        //用户默认依旧采用内存用户,可用Identity替换
       .AddTestUsers(InMemoryConfig.Users().ToList());

} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     //初始化数据(内容后面描述)
     SeedData.InitData(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServer(); app.UseAuthentication();
//使用默认UI,必须添加
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

 4、迁移数据

  迁移方式有多种方式:

  1、打开包控制台,执行以下命令:

1 add-migration InitialPersistedGrantDb -c PersistedGrantDbContext -o Migrations/IdentityServer/PersistedGrantDb
2 add-migration InitialConfigurationDb -c ConfigurationDbContext -o Migrations/IdentityServer/ConfigurationDb
3 update-database -c PersistedGrantDbContext
4 update-database -c ConfigurationDbContext

   2、在项目路径中执行命令行:

1 dotnet ef migrations add InitialPersistedGrantDb -c PersistedGrantDbContext -o Migrations/IdentityServer/PersistedGrantDb
2 dotnet ef migrations add InitialConfigurationDb -c ConfigurationDbContext -o Migrations/IdentityServer/ConfigurationDb
3 dotnet ef database update -c PersistedGrantDbContext
4 dotnet ef database update -c ConfigurationDbContext  

二、数据表含义

    数据结构迁移完成我们来看下创建了那些表:

   

  根据不同的数据库上下文划分如下图:

  

三、初始化数据

  1、创建文件SeedData.cs文件用于初始化基础数据:

public class SeedData
{
public static void InitData(IApplicationBuilder serviceProvider)
{
Console.WriteLine("开始创建初始化数据...");
using (var scope = serviceProvider.ApplicationServices.CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
{
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
EnsureSeedData(context);
}
}
Console.WriteLine("初始化数据创建完成.");
} private static void EnsureSeedData(ConfigurationDbContext context)
{
if (!context.Clients.Any())
{
Console.WriteLine("Clients 正在初始化");
foreach (var client in InMemoryConfig.GetClients())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
} if (!context.IdentityResources.Any())
{
Console.WriteLine("IdentityResources 正在初始化");
foreach (var resource in InMemoryConfig.GetIdentityResources())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
} if (!context.ApiResources.Any())
{
Console.WriteLine("ApiResources 正在初始化");
foreach (var resource in InMemoryConfig.GetApiResources())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
} if (!context.ApiScopes.Any())
{
Console.WriteLine("ApiScopes 正在初始化");
foreach (var resource in InMemoryConfig.GetApiScopes())
{
context.ApiScopes.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}

  2、并在Startup文件中添加:

 //初始化数据(内容后面描述)
SeedData.InitData(app);

  程序运行如下: 

  

  3、初始化主要数据结果如下图:

  

 4、运行效果同上一篇文章效果相同

  

四、其他

  本篇主要介绍了简单使用IdentityServer4.EntityFramework持久化存储相关配置数据和操作数据;本篇中用户信息未持久化存储未介绍,因为IdentityServer4本就支持了接入其他认证方式,如 : NetCore 官方的 Identity,可以快速实现用户管理。

  Github:https://github.com/cwsheng/IdentityServer.Demo 

认证授权:IdentityServer4 - 数据持久化的更多相关文章

  1. 基于 IdentityServer3 实现 OAuth 2.0 授权服务数据持久化

    最近花了一点时间,阅读了IdentityServer的源码,大致了解项目整体的抽象思维.面向对象的重要性; 生产环境如果要使用 IdentityServer3 ,主要涉及授权服务,资源服务的部署负载的 ...

  2. 基于IdentityServer4 实现.NET Core的认证授权

    IdentityServer4是什么? IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现. OpenID ...

  3. IdentityServer4系列 | 支持数据持久化

    一.前言 在前面的篇章介绍中,一些基础配置如API资源.客户端资源等数据以及使用过程中发放的令牌等操作数据,我们都是通过将操作数据和配置数据存储在内存中进行实现的,而在实际开发生产中,我们需要考虑如何 ...

  4. 授权认证(IdentityServer4)

    区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...

  5. 一看就懂的IdentityServer4认证授权设计方案

    查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...

  6. .net core gRPC与IdentityServer4集成认证授权

    前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...

  7. 认证授权:IdentityServer4

    前言 上一篇文章<学习OIDC>介绍了OIDC协议,本篇开始我们就来具体来学习OIDC的具体实现IdentityServer4 学习. 一.IdentityServer4 是什么? Ide ...

  8. 一站式WebAPI与认证授权服务

    保护WEBAPI有哪些方法? 微软官方文档推荐了好几个: Azure Active Directory Azure Active Directory B2C (Azure AD B2C)] Ident ...

  9. Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务

    在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka ...

随机推荐

  1. 【深入理解Java虚拟机】Java虚拟机运行时数据区

    Java虚拟机运行时数据区 线程私有 程序计数器 1.当前线程所执行的字节码的行号指示器. 2.唯一不会发生OutOfMemoryError的区域 3.如果执行的是java方法,计数器值为虚拟机字节码 ...

  2. Android开发java程序员常用代码,将字符串以逗号分别取出字符串String

    public class StringSplit { public static void main(String[] args) { String sourceStr = "1,2,3,4 ...

  3. Unity插件介绍——Odin

    今天把玩了一款最近的热门插件——“Odin - Inspector and Serializer”,其功能强大到让人无语,简直是开发利器,屠龙宝刀!它的功能是扩展Inspector显示,它重写和增加了 ...

  4. Azure Storage 系列(二) .NET Core Web 项目中操作 Blob 存储

    一,引言 上一篇文章,我们介绍到在实际项目中系统会产生大量的日志文件,用户上传的头像等等,同时也介绍到可以使用Azure Blob Storage 来存储项目中的一些日志文件,用户头像,用户视频等等. ...

  5. Zabbix-4.0-设置钉钉报警脚本

    问题:当服务器发生报错时,有一个信息能实现自动发送到我的手机或者应用上,以达到对服务器的实时的监控与处理.邮件与短信不能满足实时性,于是想到了钉钉的通知. 思路:在钉钉里面建一个群,群里面拉个机器人. ...

  6. 持续部署入门:基于 Kubernetes 实现滚动发布

    前言 软件世界比以往任何时候都更快.为了保持竞争力,需要尽快推出新的软件版本,而不会中断活跃用户访问,影响用户体验.越来越多企业已将其应用迁移到 Kubernetes. 在 Kubernetes 中有 ...

  7. [oracle/sql]关于清除重复,not in方案和not exists方案的对比

    有这样一张表: CREATE TABLE tb_sc ( id NUMBER not null primary key, studentid int not null, courseid int no ...

  8. MySQL查询更新所有满足条件的数据

    -- 将订单表所有的状态改成1update oc_repair_preorder a inner join (select id,`status` from oc_repair_preorder) b ...

  9. 干货:不同场景容器内获取客户端源IP的方法

    摘要:客户端和容器服务器之间可能存在多种不同形式的代理服务器,那容器中如何获取到客户端真实的源ip呢? k8s已经成为当今容器化的标准,人们在享受容器带来的高效与便利的同时,也遇到一些烦恼:客户端和容 ...

  10. oracle之三资源管理

    Oracle 资源管理 12.1 为什么要使用Oracle资源管理器 传统意义上,系统的资源分配是由OS来完成的,但是对于数据库资源,OS分配资源会带来一些问题: 以Linux为例,最为突出的一个问题 ...