1. 程式人生 > 實用技巧 >net core 配置 IdentityServer4

net core 配置 IdentityServer4

IdentityServer具有良好的擴充套件性,其中一個可擴充套件點是用於IdentityServer所需資料的儲存機制。 本快速入門介紹瞭如何配置IdentityServer以使用EntityFramework(EF)作為此資料的儲存機制(而不是使用我們迄今為止使用的記憶體中實現)。

IdentityServer4.EntityFramework元件

有兩種型別的資料需要持久化到資料庫中。 首先是配置資料(資源和客戶端),第二個是IdentityServer在使用時產生的操作資料(令牌,程式碼和使用者的授權資訊consents)。 這些儲存採用介面進行建模,我們在IdentityServer4.EntityFramework

Nuget包中提供這些介面的EF實現。

IdentityServer專案通過新增對IdentityServer4.EntityFrameworkNuget包的引用開始。

使用SqlServer

鑑於EF的靈活性,您可以使用任何EF支援的資料庫。 對於這個快速入門,我們將使用Visual Studio附帶的SqlServer的LocalDb版本。

資料庫Schema更改和使用EF遷移

IdentityServer4.EntityFramework包包含從IdentityServer的模型對映的實體類。 隨著IdentityServer的模型的改變,IdentityServer4.EntityFramework

中的實體類也會改變。 當您使用IdentityServer4.EntityFramework並隨著時間的推移升級時,您將負責自己的資料庫Schema以及實體類更改所需的更改。 管理這些變化的一種方法是使用EF遷移,這個快速入門將顯示如何完成。 如果遷移不是您的偏好,那麼您可以以任何您認為合適的方式管理架構更改。

使用EF工具進行遷移

關於EF遷移可以看我的這篇文章:http://www.cnblogs.com/stulzq/p/7717873.html

配置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專案目錄中開啟命令提示符。 在命令提示符下執行這兩個命令:

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來連線和檢查資料。

執行程式

您現在應該能夠執行任何現有的客戶端應用程式並登入,獲取令牌並呼叫API - 全部基於資料庫配置。

本文程式碼:https://gitee.com/gxiaopan/PlatformNetCore
原文:https://www.cnblogs.com/stulzq/p/8120518.html