时间:2021-07-01 10:21:17 帮助过:20人阅读
二、客户端和资源的数据库存储
前文我们使用的是 AddInMemory 的方式加载配置数据,接下来使用数据库连接方式加载配置数据
1.初始化及构造
public IConfiguration Configuration { get; } public IHostingEnvironment Environment { get; } public Startup(IConfiguration configuration, IHostingEnvironment environment) { Configuration = configuration; Environment = environment; }
2.定义数据库连接及获取项目名称
string connectionString = Configuration.GetConnectionString("SSOConnection"); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
3.注释 AddInMemory 方式
AddInMemoryIdentityResources(Config.GetIdentityResources())
AddInMemoryApiResources(Config.GetApis())
AddInMemoryClients(Config.GetClients())
4.添加 AddConfigurationStore
.AddConfigurationStore(opt => { opt.ConfigureDbContext = context => { context.UseMySql(connectionString, sql => { sql.MigrationsAssembly(migrationsAssembly); }); }; })
5.配置客户端和资源数据表,把项目设为启动项目,打开程序包管理器控制台,控制台设置默认项目,在控制台执行以下指令添加数据表
add-migration ConfigDbContext -c ConfigurationDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
6.更新数据库
update-database
7.将 Configs 中的配置数据添加到数据库,在 Start.cs 中执行进行初始化
private void InitializeDatabase(IApplicationBuilder app) { using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>(); if (!context.Clients.Any()) { foreach (var client in Configs.GetClients()) { context.Clients.Add(client.ToEntity()); } context.SaveChanges(); } if (!context.IdentityResources.Any()) { foreach (var resource in Configs.GetIdentityResources()) { context.IdentityResources.Add(resource.ToEntity()); } context.SaveChanges(); } if (!context.ApiResources.Any()) { foreach (var resource in Configs.GetApis()) { context.ApiResources.Add(resource.ToEntity()); } context.SaveChanges(); } } }
三、令牌和授权码的数据库存储
1.添加 AddOperationalStore
.AddOperationalStore(opt => { opt.ConfigureDbContext = context => { context.UseMySql(connectionString, sql => { sql.MigrationsAssembly(migrationsAssembly); }); }; opt.EnableTokenCleanup = true; opt.TokenCleanupInterval = 30; })
2.配置令牌和授权码数据表,把项目设为启动项目,打开程序包管理器控制台,控制台设置默认项目,在控制台执行以下指令添加数据表
add-migration OperationContext -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/OperationDb
3.更新数据库
update-database -c PersistedGrantDbContext
(三)IdentityServer4 结合 Mysql 之初体验
标签:构造 ase ipaddr source 资源 gets required store ddc