【.NET Core專案實戰-統一認證平臺】第九章 授權篇-使用Dapper持久化IdentityServer4
ofollow,noindex" target="_blank"> 【.NET Core專案實戰-統一認證平臺】開篇及目錄索引
上篇文章介紹了 IdentityServer4
的原始碼分析的內容,讓我們知道了 IdentityServer4
的一些執行原理,這篇將介紹如何使用dapper來持久化 Identityserver4
,讓我們對 IdentityServer4
理解更透徹,並優化下資料請求,減少不必要的開銷。
.netcore專案實戰交流群(637326624),有興趣的朋友可以在群裡交流討論。
一、資料如何實現持久化
在進行資料持久化之前,我們要了解 Ids4
是如何實現持久化的呢? Ids4
預設是使用記憶體實現的 IClientStore、IResourceStore、IPersistedGrantStore
三個介面,對應的分別是 InMemoryClientStore、InMemoryResourcesStore、InMemoryPersistedGrantStore
三個方法,這顯然達不到我們持久化的需求,因為都是從記憶體裡提取配置資訊,所以我們要做到 Ids4
配置資訊持久化,就需要實現這三個介面,作為優秀的身份認證框架,肯定已經幫我們想到了這點啦,有個EFCore的持久化實現,GitHub地址 https://github.com/IdentityServer/IdentityServer4.EntityFramework ,是不是萬事大吉了呢?拿來直接使用吧,使用肯定是沒有問題的,但是我們要分析下實現的方式和資料庫結構,便於後續使用dapper來持久化和擴充套件成任意資料庫儲存。
下面以 IClientStore介面 介面為例,講解下如何實現資料持久化的。他的方法就是通過clientId獲取Client記錄,乍一看很簡單,不管是用記憶體或資料庫都可以很簡單實現。
Task<Client> FindClientByIdAsync(string clientId);
要看這個介面實際用途,就可以直接檢視這個介面被注入到哪些方法中,最簡單的方式就是 Ctrl+F
,通過查詢會發現,Client實體裡有很多關聯記錄也會被用到,因此我們在提取Client資訊時需要提取他對應的關聯實體,那如果是資料庫持久化,那應該怎麼提取呢?這裡可以參考 IdentityServer4.EntityFramework
專案,我們執行下客戶端授權如下圖所示,您會發現能夠正確返回結果,但是這裡執行了哪些SQL查詢呢?

從EFCore實現中可以看出來,就一個簡單的客戶端查詢語句,盡然執行了10次資料庫查詢操作(可以使用SQL Server Profiler檢視詳細的SQL語句),這也是為什麼使用IdentityServer4獲取授權資訊時奇慢無比的原因。
public Task<Client> FindClientByIdAsync(string clientId) { var client = _context.Clients .Include(x => x.AllowedGrantTypes) .Include(x => x.RedirectUris) .Include(x => x.PostLogoutRedirectUris) .Include(x => x.AllowedScopes) .Include(x => x.ClientSecrets) .Include(x => x.Claims) .Include(x => x.IdentityProviderRestrictions) .Include(x => x.AllowedCorsOrigins) .Include(x => x.Properties) .FirstOrDefault(x => x.ClientId == clientId); var model = client?.ToModel(); _logger.LogDebug("{clientId} found in database: {clientIdFound}", clientId, model != null); return Task.FromResult(model); }
這肯定不是實際生產環境中想要的結果,我們希望是儘量一次連線查詢到想要的結果。其他2個方法類似,就不一一介紹了,我們需要使用dapper來持久化儲存,減少對伺服器查詢的開銷。
特別需要注意的是,在使用 refresh_token
時,有個有效期的問題,所以需要通過可配置的方式設定定期清除過期的授權資訊,實現方式可以通過資料庫作業、定時器、後臺任務等,使用 dapper
持久化時也需要實現此方法。
二、使用Dapper持久化
下面就開始搭建Dapper的持久化儲存,首先建一個 IdentityServer4.Dapper
類庫專案,來實現自定義的擴充套件功能,還記得前幾篇開發中間件的思路嗎?這裡再按照設計思路回顧下,首先我們考慮需要注入什麼來解決 Dapper
的使用,通過分析得知需要一個連線字串和使用哪個資料庫,以及配置定時刪除過期授權的策略。
新建 IdentityServerDapperBuilderExtensions
類,實現我們注入的擴充套件,程式碼如下。
using IdentityServer4.Dapper.Options; using System; using IdentityServer4.Stores; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 使用Dapper擴充套件 /// </summary> public static class IdentityServerDapperBuilderExtensions { /// <summary> /// 配置Dapper介面和實現(預設使用SqlServer) /// </summary> /// <param name="builder">The builder.</param> /// <param name="storeOptionsAction">儲存配置資訊</param> /// <returns></returns> public static IIdentityServerBuilder AddDapperStore( this IIdentityServerBuilder builder, Action<DapperStoreOptions> storeOptionsAction = null) { var options = new DapperStoreOptions(); builder.Services.AddSingleton(options); storeOptionsAction?.Invoke(options); builder.Services.AddTransient<IClientStore, SqlServerClientStore>(); builder.Services.AddTransient<IResourceStore, SqlServerResourceStore>(); builder.Services.AddTransient<IPersistedGrantStore, SqlServerPersistedGrantStore>(); return builder; } /// <summary> /// 使用Mysql儲存 /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IIdentityServerBuilder UseMySql(this IIdentityServerBuilder builder) { builder.Services.AddTransient<IClientStore, MySqlClientStore>(); builder.Services.AddTransient<IResourceStore, MySqlResourceStore>(); builder.Services.AddTransient<IPersistedGrantStore, MySqlPersistedGrantStore>(); return builder; } } }
整體框架基本確認了,現在就需要解決這裡用到的幾個配置資訊和實現。
-
DapperStoreOptions需要接收那些引數?
-
如何使用dapper實現儲存的三個介面資訊?
首先我們定義下配置檔案,用來接收資料庫的連線字串和配置清理的引數並設定預設值。
namespace IdentityServer4.Dapper.Options { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 配置儲存資訊 /// </summary> public class DapperStoreOptions { /// <summary> /// 是否啟用自定清理Token /// </summary> public bool EnableTokenCleanup { get; set; } = false; /// <summary> /// 清理token週期(單位秒),預設1小時 /// </summary> public int TokenCleanupInterval { get; set; } = 3600; /// <summary> /// 連線字串 /// </summary> public string DbConnectionStrings { get; set; } } }
如上圖所示,這裡定義了最基本的配置資訊,來滿足我們的需求。
下面開始來實現客戶端儲存, SqlServerClientStore
類程式碼如下。
using Dapper; using IdentityServer4.Dapper.Mappers; using IdentityServer4.Dapper.Options; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.Extensions.Logging; using System.Data.SqlClient; using System.Threading.Tasks; namespace IdentityServer4.Dapper.Stores.SqlServer { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 實現提取客戶端儲存資訊 /// </summary> public class SqlServerClientStore: IClientStore { private readonly ILogger<SqlServerClientStore> _logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerClientStore(ILogger<SqlServerClientStore> logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } /// <summary> /// 根據客戶端ID 獲取客戶端資訊內容 /// </summary> /// <param name="clientId"></param> /// <returns></returns> public async Task<Client> FindClientByIdAsync(string clientId) { var cModel = new Client(); var _client = new Entities.Client(); using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { //由於後續未用到,暫不實現 ClientPostLogoutRedirectUris ClientClaims ClientIdPRestrictions ClientCorsOrigins ClientProperties,有需要的自行新增。 string sql = @"select * from Clients where ClientId=@client and Enabled=1; select t2.* from Clients t1 inner join ClientGrantTypes t2 on t1.Id=t2.ClientId where t1.ClientId=@client and Enabled=1; select t2.* from Clients t1 inner join ClientRedirectUris t2 on t1.Id=t2.ClientId where t1.ClientId=@client and Enabled=1; select t2.* from Clients t1 inner join ClientScopes t2 on t1.Id=t2.ClientId where t1.ClientId=@client and Enabled=1; select t2.* from Clients t1 inner join ClientSecrets t2 on t1.Id=t2.ClientId where t1.ClientId=@client and Enabled=1; "; var multi = await connection.QueryMultipleAsync(sql, new { client = clientId }); var client = multi.Read<Entities.Client>(); var ClientGrantTypes = multi.Read<Entities.ClientGrantType>(); var ClientRedirectUris = multi.Read<Entities.ClientRedirectUri>(); var ClientScopes = multi.Read<Entities.ClientScope>(); var ClientSecrets = multi.Read<Entities.ClientSecret>(); if (client != null && client.AsList().Count > 0) {//提取資訊 _client = client.AsList()[0]; _client.AllowedGrantTypes = ClientGrantTypes.AsList(); _client.RedirectUris = ClientRedirectUris.AsList(); _client.AllowedScopes = ClientScopes.AsList(); _client.ClientSecrets = ClientSecrets.AsList(); cModel = _client.ToModel(); } } _logger.LogDebug("{clientId} found in database: {clientIdFound}", clientId, _client != null); return cModel; } } }
這裡面涉及到幾個知識點,第一 dapper
的高階使用,一次性提取多個數據集,然後逐一賦值, 需要注意的是sql查詢順序和賦值順序需要完全一致 。第二是 AutoMapper
的實體對映,最後封裝的一句程式碼就是 _client.ToModel();
即可完成,這與這塊使用還不是很清楚,可學習相關知識後再看,詳細的對映程式碼如下。
using System.Collections.Generic; using System.Security.Claims; using AutoMapper; namespace IdentityServer4.Dapper.Mappers { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 客戶端實體對映 /// </summary> /// <seealso cref="AutoMapper.Profile" /> public class ClientMapperProfile : Profile { public ClientMapperProfile() { CreateMap<Entities.ClientProperty, KeyValuePair<string, string>>() .ReverseMap(); CreateMap<Entities.Client, IdentityServer4.Models.Client>() .ForMember(dest => dest.ProtocolType, opt => opt.Condition(srs => srs != null)) .ReverseMap(); CreateMap<Entities.ClientCorsOrigin, string>() .ConstructUsing(src => src.Origin) .ReverseMap() .ForMember(dest => dest.Origin, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientIdPRestriction, string>() .ConstructUsing(src => src.Provider) .ReverseMap() .ForMember(dest => dest.Provider, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientClaim, Claim>(MemberList.None) .ConstructUsing(src => new Claim(src.Type, src.Value)) .ReverseMap(); CreateMap<Entities.ClientScope, string>() .ConstructUsing(src => src.Scope) .ReverseMap() .ForMember(dest => dest.Scope, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientPostLogoutRedirectUri, string>() .ConstructUsing(src => src.PostLogoutRedirectUri) .ReverseMap() .ForMember(dest => dest.PostLogoutRedirectUri, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientRedirectUri, string>() .ConstructUsing(src => src.RedirectUri) .ReverseMap() .ForMember(dest => dest.RedirectUri, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientGrantType, string>() .ConstructUsing(src => src.GrantType) .ReverseMap() .ForMember(dest => dest.GrantType, opt => opt.MapFrom(src => src)); CreateMap<Entities.ClientSecret, IdentityServer4.Models.Secret>(MemberList.Destination) .ForMember(dest => dest.Type, opt => opt.Condition(srs => srs != null)) .ReverseMap(); } } }
using AutoMapper; namespace IdentityServer4.Dapper.Mappers { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 客戶端資訊對映 /// </summary> public static class ClientMappers { static ClientMappers() { Mapper = new MapperConfiguration(cfg => cfg.AddProfile<ClientMapperProfile>()) .CreateMapper(); } internal static IMapper Mapper { get; } public static Models.Client ToModel(this Entities.Client entity) { return Mapper.Map<Models.Client>(entity); } public static Entities.Client ToEntity(this Models.Client model) { return Mapper.Map<Entities.Client>(model); } } }
這樣就完成了從資料庫裡提取客戶端資訊及相關關聯表記錄,只需要一次連線即可完成,奈斯,達到我們的要求。接著繼續實現其他2個介面,下面直接列出2個類的實現程式碼。
SqlServerResourceStore.cs
using Dapper; using IdentityServer4.Dapper.Mappers; using IdentityServer4.Dapper.Options; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; using System.Linq; namespace IdentityServer4.Dapper.Stores.SqlServer { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 重寫資源儲存方法 /// </summary> public class SqlServerResourceStore : IResourceStore { private readonly ILogger<SqlServerResourceStore> _logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerResourceStore(ILogger<SqlServerResourceStore> logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } /// <summary> /// 根據api名稱獲取相關資訊 /// </summary> /// <param name="name"></param> /// <returns></returns> public async Task<ApiResource> FindApiResourceAsync(string name) { var model = new ApiResource(); using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = @"select * from ApiResources where Name=@Name and Enabled=1; select * from ApiResources t1 inner join ApiScopes t2 on t1.Id=t2.ApiResourceId where t1.Name=@name and Enabled=1; "; var multi = await connection.QueryMultipleAsync(sql, new { name }); var ApiResources = multi.Read<Entities.ApiResource>(); var ApiScopes = multi.Read<Entities.ApiScope>(); if (ApiResources != null && ApiResources.AsList()?.Count > 0) { var apiresource = ApiResources.AsList()[0]; apiresource.Scopes = ApiScopes.AsList(); if (apiresource != null) { _logger.LogDebug("Found {api} API resource in database", name); } else { _logger.LogDebug("Did not find {api} API resource in database", name); } model = apiresource.ToModel(); } } return model; } /// <summary> /// 根據作用域資訊獲取介面資源 /// </summary> /// <param name="scopeNames"></param> /// <returns></returns> public async Task<IEnumerable<ApiResource>> FindApiResourcesByScopeAsync(IEnumerable<string> scopeNames) { var apiResourceData = new List<ApiResource>(); string _scopes = ""; foreach (var scope in scopeNames) { _scopes += "'" + scope + "',"; } if (_scopes == "") { return null; } else { _scopes = _scopes.Substring(0, _scopes.Length - 1); } string sql = "select distinct t1.* from ApiResources t1 inner join ApiScopes t2 on t1.Id=t2.ApiResourceId where t2.Name in(" + _scopes + ") and Enabled=1;"; using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { var apir = (await connection.QueryAsync<Entities.ApiResource>(sql))?.AsList(); if (apir != null && apir.Count > 0) { foreach (var apimodel in apir) { sql = "select * from ApiScopes where ApiResourceId=@id"; var scopedata = (await connection.QueryAsync<Entities.ApiScope>(sql, new { id = apimodel.Id }))?.AsList(); apimodel.Scopes = scopedata; apiResourceData.Add(apimodel.ToModel()); } _logger.LogDebug("Found {scopes} API scopes in database", apiResourceData.SelectMany(x => x.Scopes).Select(x => x.Name)); } } return apiResourceData; } /// <summary> /// 根據scope獲取身份資源 /// </summary> /// <param name="scopeNames"></param> /// <returns></returns> public async Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeAsync(IEnumerable<string> scopeNames) { var apiResourceData = new List<IdentityResource>(); string _scopes = ""; foreach (var scope in scopeNames) { _scopes += "'" + scope + "',"; } if (_scopes == "") { return null; } else { _scopes = _scopes.Substring(0, _scopes.Length - 1); } using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { //暫不實現 IdentityClaims string sql = "select * from IdentityResources where Enabled=1 and Name in(" + _scopes + ")"; var data = (await connection.QueryAsync<Entities.IdentityResource>(sql))?.AsList(); if (data != null && data.Count > 0) { foreach (var model in data) { apiResourceData.Add(model.ToModel()); } } } return apiResourceData; } /// <summary> /// 獲取所有資源實現 /// </summary> /// <returns></returns> public async Task<Resources> GetAllResourcesAsync() { var apiResourceData = new List<ApiResource>(); var identityResourceData = new List<IdentityResource>(); using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from IdentityResources where Enabled=1"; var data = (await connection.QueryAsync<Entities.IdentityResource>(sql))?.AsList(); if (data != null && data.Count > 0) { foreach (var m in data) { identityResourceData.Add(m.ToModel()); } } //獲取apiresource sql = "select * from ApiResources where Enabled=1"; var apidata = (await connection.QueryAsync<Entities.ApiResource>(sql))?.AsList(); if (apidata != null && apidata.Count > 0) { foreach (var m in apidata) { sql = "select * from ApiScopes where ApiResourceId=@id"; var scopedata = (await connection.QueryAsync<Entities.ApiScope>(sql, new { id = m.Id }))?.AsList(); m.Scopes = scopedata; apiResourceData.Add(m.ToModel()); } } } var model = new Resources(identityResourceData, apiResourceData); return model; } } }
SqlServerPersistedGrantStore.cs
using Dapper; using IdentityServer4.Dapper.Mappers; using IdentityServer4.Dapper.Options; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Dapper.Stores.SqlServer { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 重寫授權資訊儲存 /// </summary> public class SqlServerPersistedGrantStore : IPersistedGrantStore { private readonly ILogger<SqlServerPersistedGrantStore> _logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerPersistedGrantStore(ILogger<SqlServerPersistedGrantStore> logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } /// <summary> /// 根據使用者標識獲取所有的授權資訊 /// </summary> /// <param name="subjectId">使用者標識</param> /// <returns></returns> public async Task<IEnumerable<PersistedGrant>> GetAllAsync(string subjectId) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from PersistedGrants where SubjectId=@subjectId"; var data = (await connection.QueryAsync<Entities.PersistedGrant>(sql, new { subjectId }))?.AsList(); var model = data.Select(x => x.ToModel()); _logger.LogDebug("{persistedGrantCount} persisted grants found for {subjectId}", data.Count, subjectId); return model; } } /// <summary> /// 根據key獲取授權資訊 /// </summary> /// <param name="key">認證資訊</param> /// <returns></returns> public async Task<PersistedGrant> GetAsync(string key) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from PersistedGrants where [Key]=@key"; var result = await connection.QueryFirstOrDefaultAsync<Entities.PersistedGrant>(sql, new { key }); var model = result.ToModel(); _logger.LogDebug("{persistedGrantKey} found in database: {persistedGrantKeyFound}", key, model != null); return model; } } /// <summary> /// 根據使用者標識和客戶端ID移除所有的授權資訊 /// </summary> /// <param name="subjectId">使用者標識</param> /// <param name="clientId">客戶端ID</param> /// <returns></returns> public async Task RemoveAllAsync(string subjectId, string clientId) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "delete from PersistedGrants where ClientId=@clientId and SubjectId=@subjectId"; await connection.ExecuteAsync(sql, new { subjectId, clientId }); _logger.LogDebug("remove {subjectId} {clientId} from database success", subjectId, clientId); } } /// <summary> /// 移除指定的標識、客戶端、型別等授權資訊 /// </summary> /// <param name="subjectId">標識</param> /// <param name="clientId">客戶端ID</param> /// <param name="type">授權型別</param> /// <returns></returns> public async Task RemoveAllAsync(string subjectId, string clientId, string type) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "delete from PersistedGrants where ClientId=@clientId and SubjectId=@subjectId and Type=@type"; await connection.ExecuteAsync(sql, new { subjectId, clientId }); _logger.LogDebug("remove {subjectId} {clientId} {type} from database success", subjectId, clientId, type); } } /// <summary> /// 移除指定KEY的授權資訊 /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task RemoveAsync(string key) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "delete from PersistedGrants where [Key]=@key"; await connection.ExecuteAsync(sql, new { key }); _logger.LogDebug("remove {key} from database success", key); } } /// <summary> /// 儲存授權資訊 /// </summary> /// <param name="grant">實體</param> /// <returns></returns> public async Task StoreAsync(PersistedGrant grant) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { //移除防止重複 await RemoveAsync(grant.Key); string sql = "insert into PersistedGrants([Key],ClientId,CreationTime,Data,Expiration,SubjectId,Type) values(@Key,@ClientId,@CreationTime,@Data,@Expiration,@SubjectId,@Type)"; await connection.ExecuteAsync(sql, grant); } } } }
使用dapper提取儲存資料已經全部實現完,接下來我們需要實現定時清理過期的授權資訊。
首先定義一個清理過期資料介面 IPersistedGrants
,定義如下所示。
using System; using System.Threading.Tasks; namespace IdentityServer4.Dapper.Interfaces { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 過期授權清理介面 /// </summary> public interface IPersistedGrants { /// <summary> /// 移除指定時間的過期資訊 /// </summary> /// <param name="dt">過期時間</param> /// <returns></returns> Task RemoveExpireToken(DateTime dt); } }
現在我們來實現下此介面,詳細程式碼如下。
using Dapper; using IdentityServer4.Dapper.Interfaces; using IdentityServer4.Dapper.Options; using Microsoft.Extensions.Logging; using System; using System.Data.SqlClient; using System.Threading.Tasks; namespace IdentityServer4.Dapper.Stores.SqlServer { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 實現授權資訊自定義管理 /// </summary> public class SqlServerPersistedGrants : IPersistedGrants { private readonly ILogger<SqlServerPersistedGrants> _logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerPersistedGrants(ILogger<SqlServerPersistedGrants> logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } /// <summary> /// 移除指定的時間過期授權資訊 /// </summary> /// <param name="dt">Utc時間</param> /// <returns></returns> public async Task RemoveExpireToken(DateTime dt) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "delete from PersistedGrants where Expiration>@dt"; await connection.ExecuteAsync(sql, new { dt }); } } } }
有個清理的介面和實現,我們需要注入下實現 builder.Services.AddTransient<IPersistedGrants, SqlServerPersistedGrants>();
,接下來就是開啟後端服務來清理過期記錄。
using IdentityServer4.Dapper.Interfaces; using IdentityServer4.Dapper.Options; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace IdentityServer4.Dapper.HostedServices { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 清理過期Token方法 /// </summary> public class TokenCleanup { private readonly ILogger<TokenCleanup> _logger; private readonly DapperStoreOptions _options; private readonly IPersistedGrants _persistedGrants; private CancellationTokenSource _source; public TimeSpan CleanupInterval => TimeSpan.FromSeconds(_options.TokenCleanupInterval); public TokenCleanup(IPersistedGrants persistedGrants, ILogger<TokenCleanup> logger, DapperStoreOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); if (_options.TokenCleanupInterval < 1) throw new ArgumentException("Token cleanup interval must be at least 1 second"); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _persistedGrants = persistedGrants; } public void Start() { Start(CancellationToken.None); } public void Start(CancellationToken cancellationToken) { if (_source != null) throw new InvalidOperationException("Already started. Call Stop first."); _logger.LogDebug("Starting token cleanup"); _source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); Task.Factory.StartNew(() => StartInternal(_source.Token)); } public void Stop() { if (_source == null) throw new InvalidOperationException("Not started. Call Start first."); _logger.LogDebug("Stopping token cleanup"); _source.Cancel(); _source = null; } private async Task StartInternal(CancellationToken cancellationToken) { while (true) { if (cancellationToken.IsCancellationRequested) { _logger.LogDebug("CancellationRequested. Exiting."); break; } try { await Task.Delay(CleanupInterval, cancellationToken); } catch (TaskCanceledException) { _logger.LogDebug("TaskCanceledException. Exiting."); break; } catch (Exception ex) { _logger.LogError("Task.Delay exception: {0}. Exiting.", ex.Message); break; } if (cancellationToken.IsCancellationRequested) { _logger.LogDebug("CancellationRequested. Exiting."); break; } ClearTokens(); } } public void ClearTokens() { try { _logger.LogTrace("Querying for tokens to clear"); //提取滿足條件的資訊進行刪除 _persistedGrants.RemoveExpireToken(DateTime.UtcNow); } catch (Exception ex) { _logger.LogError("Exception clearing tokens: {exception}", ex.Message); } } } }
using IdentityServer4.Dapper.Options; using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks; namespace IdentityServer4.Dapper.HostedServices { /// <summary> /// 金焰的世界 /// 2018-12-03 /// 授權後端清理服務 /// </summary> public class TokenCleanupHost : IHostedService { private readonly TokenCleanup _tokenCleanup; private readonly DapperStoreOptions _options; public TokenCleanupHost(TokenCleanup tokenCleanup, DapperStoreOptions options) { _tokenCleanup = tokenCleanup; _options = options; } public Task StartAsync(CancellationToken cancellationToken) { if (_options.EnableTokenCleanup) { _tokenCleanup.Start(cancellationToken); } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { if (_options.EnableTokenCleanup) { _tokenCleanup.Stop(); } return Task.CompletedTask; } } }
是不是實現一個定時任務很簡單呢?功能完成別忘了注入實現,現在我們使用dapper持久化的功能基本完成了。
builder.Services.AddSingleton<TokenCleanup>(); builder.Services.AddSingleton<IHostedService, TokenCleanupHost>();
三、測試功能應用
在前面客戶端授權中,我們增加dapper擴充套件的實現,來測試功能是否能正常使用,且使用 SQL Server Profiler
來監控下呼叫的過程。可以從之前文章中的原始碼 TestIds4
專案中,實現持久化的儲存,改造注入程式碼如下。
services.AddIdentityServer() .AddDeveloperSigningCredential() //.AddInMemoryApiResources(Config.GetApiResources()) //.AddInMemoryClients(Config.GetClients()); .AddDapperStore(option=> { option.DbConnectionStrings = "Server=192.168.1.114;Database=mpc_identity;User ID=sa;Password=bl123456;"; });
好了,現在可以配合閘道器來測試下客戶端登入了,開啟 PostMan
,啟用本地的專案,然後訪問之前配置的客戶端授權地址,並開啟SqlServer監控,檢視執行程式碼。

訪問能夠得到我們預期的結果且查詢全部是dapper寫的Sql語句。且定期清理任務也啟動成功,會根據配置的引數來執行清理過期授權資訊。
四、使用Mysql儲存並測試
這裡Mysql重寫就不一一列出來了,語句跟sqlserver幾乎是完全一樣,然後呼叫 .UseMySql()
即可完成mysql切換,我花了不到2分鐘就完成了Mysql的所有語句和切換功能,是不是簡單呢?接著測試Mysql應用,程式碼如下。
services.AddIdentityServer() .AddDeveloperSigningCredential() //.AddInMemoryApiResources(Config.GetApiResources()) //.AddInMemoryClients(Config.GetClients()); .AddDapperStore(option=> { option.DbConnectionStrings = "Server=*******;Database=mpc_identity;User ID=root;Password=*******;"; }).UseMySql();
可以返回正確的結果資料,擴充套件Mysql實現已經完成,如果想用其他資料庫實現,直接按照我寫的方法擴充套件下即可。
五、總結及預告
本篇我介紹瞭如何使用 Dapper
來持久化 Ids4
資訊,並介紹了實現過程,然後實現了 SqlServer
和 Mysql
兩種方式,也介紹了使用過程中遇到的技術問題,其實在實現過程中我發現的一個快取和如何讓授權資訊立即過期等問題,這塊大家可以一起先思考下如何實現,後續文章中我會介紹具體的實現方式,然後把快取遷移到 Redis
裡。
下一篇開始就正式介紹Ids4的幾種授權方式和具體的應用,以及如何在我們客戶端進行整合,如果在學習過程中遇到不懂或未理解的問題,歡迎大家加入QQ群聊 637326624
與作者聯絡吧。