认证授权:IdentityServer4 - 数据持久化
前言:
前面的文章中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 - 数据持久化的更多相关文章
- 基于 IdentityServer3 实现 OAuth 2.0 授权服务数据持久化
最近花了一点时间,阅读了IdentityServer的源码,大致了解项目整体的抽象思维.面向对象的重要性; 生产环境如果要使用 IdentityServer3 ,主要涉及授权服务,资源服务的部署负载的 ...
- 基于IdentityServer4 实现.NET Core的认证授权
IdentityServer4是什么? IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现. OpenID ...
- IdentityServer4系列 | 支持数据持久化
一.前言 在前面的篇章介绍中,一些基础配置如API资源.客户端资源等数据以及使用过程中发放的令牌等操作数据,我们都是通过将操作数据和配置数据存储在内存中进行实现的,而在实际开发生产中,我们需要考虑如何 ...
- 授权认证(IdentityServer4)
区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...
- 一看就懂的IdentityServer4认证授权设计方案
查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...
- .net core gRPC与IdentityServer4集成认证授权
前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...
- 认证授权:IdentityServer4
前言 上一篇文章<学习OIDC>介绍了OIDC协议,本篇开始我们就来具体来学习OIDC的具体实现IdentityServer4 学习. 一.IdentityServer4 是什么? Ide ...
- 一站式WebAPI与认证授权服务
保护WEBAPI有哪些方法? 微软官方文档推荐了好几个: Azure Active Directory Azure Active Directory B2C (Azure AD B2C)] Ident ...
- Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务
在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka ...
随机推荐
- vue刷新数组
困扰我两天的问题被一行代码解决了!!! 最近在做某个功能时用到了v-for,页面内容都是根据父页面传递过来的数组生成的,但是当我改变数组内容时页面不会跟着改变.这个问题足足困扰了我两天时间,最终下面的 ...
- Matrix4x4
Unity3D开发之Matrix4x4矩阵变换 https://www.cnblogs.com/hewei2012/p/4190282.html Matrix4x4 4x4矩阵 http://wiki ...
- ParticleSystem 介绍
ParticleSystem 介绍 http://gad.qq.com/article/detail/31724
- C# .NET容器的源码
这里有List<T>的源码http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
- 算法专题 | 10行代码实现的最短路算法——Bellman-ford与SPFA
今天是算法数据结构专题的第33篇文章,我们一起来聊聊最短路问题. 最短路问题也属于图论算法之一,解决的是在一张有向图当中点与点之间的最短距离问题.最短路算法有很多,比较常用的有bellman-ford ...
- 【HttpRunner v3.x】笔记 —— 开篇
最近在社群聊天里,发现了一款适用于http协议的接口框架--HttpRunner.在对其有个大致了解后,我觉得这款框架优点多多,整合了接口测试中所配套用到的多种框架.通过优秀的封装,将case整合到一 ...
- 3 path核心模块
const path = require('path') // require('./static/test/test') { /* 总结: __dirname: 获得当前执行文件所在目录的完整目录名 ...
- 蒲公英 · JELLY技术周刊 Vol.21 -- 技术周刊 · React Hooks vs Vue 3 + Composition API
蒲公英 · JELLY技术周刊 Vol.21 选 React 还是 Vue,每个人心中都会有自己的答案,有很多理由去 pick 心水的框架,但是当我们扪心自问,我们真的可以公正的来评价这两者之间的差异 ...
- 剑指 Offer 53 - I. 在排序数组中查找数字 I
题目描述 统计一个数字在排序数组中出现的次数. 示例1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 示例2: 输入: nums = [5,7,7,8,8, ...
- 官网安装Python包太慢?教你三种下载安装方式-PiP、conda、轮子,教你三种Pytorch的下载安装方式,保证你再也不用出现Error
上一期我们介绍了CUDA下载安装以及其总结,这一期教大家如何在Anaconda中使用CUDA来进行加速.神经网络依赖cuDNN的下载安装,以及下载和安装Pytorch-GPU安装包的三种方式(cond ...