IdentityServer具有良好的擴展性,其中一個可擴展點是用於IdentityServer所需數據的存儲機制。 本快速入門介紹了如何配置IdentityServer以使用EntityFramework(EF)作為此數據的存儲機制(而不是使用我們迄今為止使用的內存中實現)。
IdentityServer4.EntityFramework組件
有兩種類型的數據需要持久化到數據庫中。 首先是配置數據(資源和客戶端),第二個是IdentityServer在使用時產生的操作數據(令牌,代碼和用戶的授權信息consents)。 這些存儲采用接口進行建模,我們在IdentityServer4.EntityFramework
Nuget包中提供這些接口的EF實現。
添加 IdentityServer項目Nuget包的引用開始。
使用SqlServer配置store
下一步是在Startup.cs中ConfigureServices方法中的AddInMemoryClients,AddInMemoryIdentityResources和AddInMemoryApiResources進行替換。 我們將用這個代碼替換它們:

您可能需要將這些命名空間添加到文件中:
using Microsoft.EntityFrameworkCore; using System.Reflection;
上面的代碼是對一個連接字符串進行硬編碼,如果你願意,你可以隨意更改。 此外,對AddConfigurationStore
和AddOperationalStore
的調用是注冊EF支持的存儲實現。
傳遞給這些API的“builder”回調方法是EF的機制,允許您為這兩個存儲中的每一個配置用於DbContext
的DbContextOptionsBuilder
。 這就是我們的DbContext類可以用你想要使用的數據庫提供程序來配置。 在這種情況下,通過調用UseSqlServer
,我們正在使用SqlServer。 你也可以知道,這是提供連接字符串的地方。
UseSqlServer中的“options”回調函數是配置定義EF遷移的程序集的方法。 EF需要使用遷移來定義數據庫的Schema。
添加遷移
要創建遷移,請在IdentityServer項目目錄中打開命令提示符。 在命令提示符下運行這兩個命令:
1.add-migration InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Migrations/IdentityServer/PersistedGrantDb
2.update-database -c PersistedGrantDbContext 3.add-migration
InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Migrations/IdentityServer/ConfigurationDb
4.update-database -c
ConfigurationDbContext
執行情況應該如下:
您現在應該在項目中看到一個〜/Migrations/IdentityServer
文件夾。 這包含新創建的遷移的代碼。
初始化數據庫
現在我們已經添加了遷移,我們可以編寫代碼來從遷移中創建數據庫。 我們還將使用我們在之前的快速入門中定義的內存配置數據對數據庫進行種子處理。
在Startup.cs中添加這個方法來幫助初始化數據庫:
private void InitializeDatabase(IApplicationBuilder app) { using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate(); var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>(); context.Database.Migrate(); if (!context.Clients.Any()) { foreach (var client in Config.Clients) { context.Clients.Add(client.ToEntity()); } context.SaveChanges(); } if (!context.IdentityResources.Any()) { foreach (var resource in Config.IdentityResources) { context.IdentityResources.Add(resource.ToEntity()); } context.SaveChanges(); } if (!context.ApiResources.Any()) { foreach (var resource in Config.ApiResources) { context.ApiResources.Add(resource.ToEntity()); } context.SaveChanges(); } } }
然后我們可以從Configure方法調用它:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // this will do the initial DB population InitializeDatabase(app); // the rest of the code that was already here // ... }
現在,如果運行IdentityServer項目,則應創建數據庫並使用快速入門配置數據進行種子插入。 您應該能夠使用SQL Server Management Studio或Visual Studio來連接和檢查數據。
配置自己的用戶數據表
1.add-migration InitMyTable -c UserContext
2.update-database -c UserContext
登錄密碼校驗
運行程序
配置成功,運行如下:
您現在應該能夠運行任何現有的客戶端應用程序並登錄,獲取令牌並調用API - 全部基於數據庫配置。
獲取Token調試如下: