(三)IdentityServer4 結合 Mysql 之初體驗


前面寫的示例中,IdeneityServer 使用的是內存緩存的存儲方式,所有的配置都寫在Config.cs里。在實際應用中,應該使用數據庫存儲方式,方便隨時配置,如添加新的用戶、資源、客戶端,也可以節省服務器內存。

本文從三個方面來實現 IdentityServer4 結合 Mysql 從而實現數據庫存儲方式,分別是客戶端及資源數據、令牌及授權碼數據以及用戶數據。

一、核心

這里的核心是有三個上下文:

1. 配置數據(資源、客戶端、身份)對應配置上下文 ConfigurationDbContext(負責數據庫中對客戶端、資源和 CORS 設置的配置存儲);

2. 操作數據(令牌,代碼和用戶的授權信息 consents)對應操作上下文 PersistedGrantDbContext(負責存儲同意、授權代碼、刷新令牌和引用令牌);

3. 用戶數據(用戶,角色,Claim)對應用戶上下文 ApplicationDbContext(實現 User、Role、Claim 之間交互)。

前兩個在 IdentityServer4 中已經封裝好了,第三個可以自定義 ApplicationDbContext 繼承 NetCore 自帶的 Identity 認證機制,也可以不繼承自定義表結構。

二、准備內容

mysql 數據庫

Nuget 所需包
IdentityServer4
IdentityServer4.EntityFramework
IdentityServer4.AspNetIdentity Pomelo.EntityFrameworkCore.MySql Microsoft.EntityFrameworkCore.Tools 新建 appsettings.json 文件添加數據庫連接字符串 {
"ConnectionStrings": { "SSOConnection": "server=ipAddress;userid=root;pwd=Password;database=DB;" } }

1.初始化及構造

public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }

public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
    Configuration = configuration;
    Environment = environment;
}

2.定義數據庫連接及獲取項目名稱

string connectionString = Configuration.GetConnectionString("SSOConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

3.注釋 AddInMemory 方式

AddInMemoryIdentityResources(Config.GetIdentityResources())
AddInMemoryApiResources(Config.GetApis())
AddInMemoryClients(Config.GetClients())

三、客戶端和資源的數據庫存儲

前文我們使用的是 AddInMemory 的方式加載配置數據,接下來使用數據庫連接方式加載配置數據

1.添加 AddConfigurationStore

.AddConfigurationStore(opt =>
{
    opt.ConfigureDbContext = context =>
    {
        context.UseMySql(connectionString, sql =>
        {
            sql.MigrationsAssembly(migrationsAssembly);
        });
    };
})

2.配置客戶端和資源數據表,把項目設為啟動項目,打開程序包管理器控制台,控制台設置默認項目,在控制台執行以下指令添加數據表

Add-Migration InitConfiguration -Context ConfigurationDbContext -o Date\Migrations\IdentityServer\ConfiguragtionDb

四、令牌和授權碼的數據庫存儲

1.添加 AddOperationalStore

.AddOperationalStore(opt =>
{
    opt.ConfigureDbContext = context =>
    {
        context.UseMySql(connectionString, sql =>
        {
            sql.MigrationsAssembly(migrationsAssembly);
        });
    };
    opt.EnableTokenCleanup = true;
    opt.TokenCleanupInterval = 30;
})

2.配置令牌和授權碼數據表,把項目設為啟動項目,打開程序包管理器控制台,控制台設置默認項目,在控制台執行以下指令添加數據表

Add-Migration InitConfiguration -Context PersistedGrantDbContext -o Date\Migrations\IdentityServer\PersistedGrantDb

五、用戶數據

1.添加 AddAspNetIdentity

.AddAspNetIdentity<ApplicationUser>()

2.添加系統配置(在數據庫連接定義后添加)

// 數據庫配置系統應用用戶數據上下文
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connectionString));

// 啟用 Identity 服務 添加指定的用戶和角色類型的默認標識系統配置
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

3.自定義 ApplicationDbContext 類,繼承 NetCore 自帶的 Identity 認證機制(也可以不繼承而自定義表結構)

// 定義用戶管理上下文,繼承 NetCore 自帶的 Identity 認證機制,也可以不繼承而自定義表結構。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

public class ApplicationUser : IdentityUser
{
    //可以在這里擴展,下文會說到
}

六、創建數據表

上述操作將會在 Startup.cs 中配置三個上下文,以及進行 Migrations 遷移,接下來分別執行以下語句將 Migrations 遷移的表創建到數據庫中

Update-Database -Context PersistedGrantDbContext
update-database -context ConfigurationDbContext
Update-Database -Context ApplicationDbContext

七、將配置數據寫入數據庫

Migrations 遷移后數據庫會生成三個上下文對應的數據表,接下來將把 Config.cs 中已配置的數據生成到數據庫中去

未完待續...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM