IdentityServer(14)- 經過EntityFramework Core持久化配置和操做數據

本文用了EF,若是不適用EF的,請參考這篇文章,實現這些接口來本身定義存儲等邏輯。http://www.cnblogs.com/stulzq/p/8144056.htmlhtml

IdentityServer具備良好的擴展性,其中一個可擴展點是用於IdentityServer所需數據的存儲機制。 本快速入門介紹瞭如何配置IdentityServer以使用EntityFramework(EF)做爲此數據的存儲機制(而不是使用咱們迄今爲止使用的內存中實現)。git

IdentityServer4.EntityFramework組件

有兩種類型的數據須要持久化到數據庫中。 首先是配置數據(資源和客戶端),第二個是IdentityServer在使用時產生的操做數據(令牌,代碼和用戶的受權信息consents)。 這些存儲採用接口進行建模,咱們在IdentityServer4.EntityFramework Nuget包中提供這些接口的EF實現。github

IdentityServer項目經過添加對IdentityServer4.EntityFramework Nuget包的引用開始。sql

使用SqlServer

鑑於EF的靈活性,您可使用任何EF支持的數據庫。 對於這個快速入門,咱們將使用Visual Studio附帶的SqlServer的LocalDb版本。shell

數據庫Schema更改和使用EF遷移

IdentityServer4.EntityFramework包包含從IdentityServer的模型映射的實體類。 隨着IdentityServer的模型的改變,IdentityServer4.EntityFramework中的實體類也會改變。 當您使用IdentityServer4.EntityFramework並隨着時間的推移升級時,您將負責本身的數據庫Schema以及實體類更改所需的更改。 管理這些變化的一種方法是使用EF遷移,這個快速入門將顯示如何完成。 若是遷移不是您的偏好,那麼您能夠以任何您認爲合適的方式管理架構更改。數據庫

爲IdentityServer4.EntityFramework中的實體維護SqlServer的SQL腳本。 https://github.com/IdentityServer/IdentityServer4.EntityFramework/tree/dev/src/Host/Migrations/IdentityServer架構

使用EF工具進行遷移

關於EF遷移能夠看個人這篇文章:http://www.cnblogs.com/stulzq/p/7717873.htmlapp

咱們須要手動更改項目的csproj文件來添加EF工具:ide

而後在結束</ Project>元素以前添加下面的代碼片斷:函數

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

看起來像這樣:

保存並關閉文件。 爲了測試你已經正確安裝了這些工具,你能夠在項目所在的目錄下打開一個命令shell並運行dotnet ef。 它應該是這樣的:

配置store

下一步是在Startup.cs中ConfigureServices方法中的AddInMemoryClients,AddInMemoryIdentityResources和AddInMemoryApiResources進行替換。 咱們將用這個代碼替換它們:

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()
    .AddDeveloperSigningCredential()
    .AddTestUsers(Config.GetUsers())
    // this adds the config data from DB (clients, resources)
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    // this adds the operational data from DB (codes, tokens, consents)
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));

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

您可能須要將這些命名空間添加到文件中:

using Microsoft.EntityFrameworkCore;
using System.Reflection;

上面的代碼是對一個鏈接字符串進行硬編碼,若是你願意,你能夠隨意更改。 此外,對AddConfigurationStoreAddOperationalStore的調用是註冊EF支持的存儲實現。

傳遞給這些API的「builder」回調方法是EF的機制,容許您爲這兩個存儲中的每個配置用於DbContextDbContextOptionsBuilder。 這就是咱們的DbContext類能夠用你想要使用的數據庫提供程序來配置。 在這種狀況下,經過調用UseSqlServer,咱們正在使用SqlServer。 你也能夠知道,這是提供鏈接字符串的地方。

UseSqlServer中的「options」回調函數是配置定義EF遷移的程序集的方法。 EF須要使用遷移來定義數據庫的Schema。

添加遷移

要建立遷移,請在IdentityServer項目目錄中打開命令提示符。 在命令提示符下運行這兩個命令:

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

執行狀況應該以下:

您如今應該在項目中看到一個〜/ 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.GetApiResources())
            {
                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來鏈接和檢查數據。

運行程序

您如今應該可以運行任何現有的客戶端應用程序並登陸,獲取令牌並調用API - 所有基於數據庫配置。

本文代碼:https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Quickstarts/7_EntityFrameworkStorage 原文:https://identityserver4.readthedocs.io/en/latest/quickstarts/7_entity_framework.html

相關文章
相關標籤/搜索