.NET Core IdentityServer4實戰 第三章-使用EntityFramework Core進行持久化配置

內容:本文帶你們使用IdentityServer4進行使用使用EntityFramework Core進行配置和操做數據git

做者:zara(張子浩) 歡迎分享,但需在文章鮮明處留下原文地址。程序員

  前兩章內容呢,不管是Client定義仍是Server端對象資源定義都是存儲與內存,固然這個問題也被博友問到,那麼咱們如何從數據庫中讀取呢,固然這個IdentityServre已經想好爲咱們進行處理了,那麼只須要安裝 IdentityServer4.EntityFramework  就能夠了。github

通常來講都會使用EF作遷移,那麼若是讓EF支持.NET Cli命令行呢,打開項目。sql

在 </project> 以前添加一下代碼,用於支持Cli命令行,再此以後你能夠去項目根目錄經過cmd.exe 執行 doenet ef,若是沒有出現error,就ok了!若是出現問題大可能是都是這個放錯位置了。數據庫

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>

鑑於EF的靈活性,咱們本篇文章使用SqlServer數據庫,就如今咱們建立一個數據庫,還有一些相關的表。app

IdentityServer4.EntityFramework.Storage中的實體維護SqlServer的最新SQL腳本他們就在這裏。(隨便建立一個數據庫,把那兩個表放進去執行就好)ide

 下面咱們要在Server進行配置了,須要在 Startup.cs 中的方法 ConfigureServices 進行修改,首先咱們定義了一個常量 connectionString ,這你確定知道,這是一個數據庫鏈接字符串,再往下定義了一個 migrationsAssembly ,它獲取了程序集的名稱,再經過 AddIdentityServer 以及 AddOperationalStore 方法對數據庫的相關遷移配置進行了賦值。ui

const string connectionString = @"Data Source=(LocalDb)\MSSQLLocalDB;database=IdentityServer4.Quickstart.EntityFramework-2.0.0;trusted_connection=yes;";
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
    .AddTestUsers(Config.GetUsers())
    // this adds the config data from DB (clients, resources)
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = b =>
            b.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    // this adds the operational data from DB (codes, tokens, consents)
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = b =>
            b.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));

        // this enables automatic token cleanup. this is optional.
        options.EnableTokenCleanup = true;
    });

   再此期間你會引用 System.Reflection 以及 Microsoft.EntityFrameworkCore ,如上面所述,上面是硬編碼形式進行配置了,更確切的說這些關於數據庫的配置都是一個叫作 ConfigurationStoreOptions 的對象,你能夠隨便修改它,EF兼容的的數據庫它都是能夠的。由於IdentityServer4實現了EF可實現的接口。this

它從哪裏實現了呢?咱們不難發現,在 IdentityServerEntityFrameworkBuilderExtensions 中的定義中有一個叫作 AddOperationalStore 的參數,它就是爲了添加動態的存儲庫,定義以下。編碼

public static IIdentityServerBuilder AddOperationalStore<TContext>(this IIdentityServerBuilder builder, Action<OperationalStoreOptions> storeOptionsAction = null) 
        where TContext : DbContext, IPersistedGrantDbContext;

可見它實現了DbContext,而你們都是.NET 程序員,因此我以爲你應該知道了怎麼回事了,就如今,請確保你的鏈接字符串正確,咱們要開始進行遷移了!執行如下命令.

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

 若是沒有什麼問題,那麼結果必定以下所示,固然您的項目中必定要安裝 Microsoft.EntityFrameworkCore ,不然將會出現 ERROR:Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding .

 您如今應該在項目中看到一個 〜/Data/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.GetClients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }
                    context.SaveChanges();
                }
                if (!context.IdentityResources.Any())
                {
                    foreach (var resource in Config.GetIdentityResources())
                    {
                        context.IdentityResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }
                if (!context.ApiResources.Any())
                {
                    foreach (var resource in Config.GetApis())
                    {
                        context.ApiResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }
            }
        }

上面的代碼可能須要將這些命名空間添加到您的文件中:

using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;

而後咱們能夠從Configure方法中調用它

public void Configure(IApplicationBuilder app)
{
    InitializeDatabase(app);
}

如今,若是運行IdentityServer項目,則應建立數據庫並使用快速入門配置數據進行種子設定。您應該可以使用SQL Server Management Studio或Visual Studio來鏈接和檢查數據。

 

  最後你能夠根據這個Client表來配置你的Config.cs中的GetUsers這樣服務端的配置也就如此了,固然你能夠自定義數據庫的字段來適應你的應用程序,那麼固然沒更新一次你就能夠經過EF的相關命令倆更新數據庫。那麼全部的更新記錄就在 __EFMigrationsHistory 表中。 

相關文章
相關標籤/搜索