前面的文章中IdentityServer4 配置內容都存儲到內存中,本篇文章開始把配置信息存儲到數據庫中;本篇文章繼續基於github的代碼來實現配置數據持久化到MySQL中git
在前面使用IDS4時,配置的一些基礎:如Api資源、客戶端等數據;以及在使用過程當中受權後發放的token、受權、受權碼等操做數據。若是持久化如何處理呢?IDS4已經提供了對應的方式 github
主要負責數據庫對客戶端、標識資源、Api資源和CORS等的配置存儲sql
主要存儲操做數據,如:受權碼、訪問令牌、刷新令牌等相關操做數據 數據庫
Install-Package IdentityServer4.EntityFramework
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Pomelo.EntityFrameworkCore.MySql
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?}"); }); } }
遷移方式有多種方式:數據結構
一、打開包控制檯,執行如下命令:app
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
二、在項目路徑中執行命令行:ide
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
數據結構遷移完成咱們來看下建立了那些表:ui
根據不一樣的數據庫上下文劃分以下圖:this
一、建立文件SeedData.cs文件用於初始化基礎數據:spa
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(); } } }
二、並在Startup文件中添加:
//初始化數據(內容後面描述) SeedData.InitData(app);
程序運行以下:
三、初始化主要數據結果以下圖:
四、運行效果同上一篇文章效果相同
本篇主要介紹了簡單使用IdentityServer4.EntityFramework持久化存儲相關配置數據和操做數據;本篇中用戶信息未持久化存儲未介紹,由於IdentityServer4本就支持了接入其餘認證方式,如 : NetCore 官方的 Identity,能夠快速實現用戶管理。