上篇文章介紹了
IdentityServer4
的源碼分析的內容,讓咱們知道了IdentityServer4
的一些運行原理,這篇將介紹如何使用dapper來持久化Identityserver4
,讓咱們對IdentityServer4
理解更透徹,並優化下數據請求,減小沒必要要的開銷。html.netcore項目實戰交流羣(637326624),有興趣的朋友能夠在羣裏交流討論。mysql
在進行數據持久化以前,咱們要了解Ids4
是如何實現持久化的呢?Ids4
默認是使用內存實現的IClientStore、IResourceStore、IPersistedGrantStore
三個接口,對應的分別是InMemoryClientStore、InMemoryResourcesStore、InMemoryPersistedGrantStore
三個方法,這顯然達不到咱們持久化的需求,由於都是從內存裏提取配置信息,因此咱們要作到Ids4
配置信息持久化,就須要實現這三個接口,做爲優秀的身份認證框架,確定已經幫咱們想到了這點啦,有個EFCore的持久化實現,GitHub地址https://github.com/IdentityServer/IdentityServer4.EntityFramework,是否是萬事大吉了呢?拿來直接使用吧,使用確定是沒有問題的,可是咱們要分析下實現的方式和數據庫結構,便於後續使用dapper來持久化和擴展成任意數據庫存儲。git
下面以IClientStore接口接口爲例,講解下如何實現數據持久化的。他的方法就是經過clientId獲取Client記錄,乍一看很簡單,不論是用內存或數據庫均可以很簡單實現。github
Task<Client> FindClientByIdAsync(string clientId);
要看這個接口實際用途,就能夠直接查看這個接口被注入到哪些方法中,最簡單的方式就是Ctrl+F
sql
,經過查找會發現,Client實體裏有不少關聯記錄也會被用到,所以咱們在提取Client信息時須要提取他對應的關聯實體,那若是是數據庫持久化,那應該怎麼提取呢?這裏能夠參考IdentityServer4.EntityFramework
項目,咱們執行下客戶端受權以下圖所示,您會發現可以正確返回結果,可是這裏執行了哪些SQL查詢呢?
數據庫
從EFCore實現中能夠看出來,就一個簡單的客戶端查詢語句,盡然執行了10次數據庫查詢操做(可使用SQL Server Profiler查看詳細的SQL語句),這也是爲何使用IdentityServer4獲取受權信息時奇慢無比的緣由。c#
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
持久化時也須要實現此方法。api
下面就開始搭建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重寫就不一一列出來了,語句跟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
與做者聯繫吧。