" 【.NET Core項目實戰 統一認證平臺】開篇及目錄索引 " 上篇文章介紹了 的源碼分析的內容,讓我們知道了 的一些運行原理,這篇將介紹如何使用dapper來持久化 ,讓我們對 理解更透徹,並優化下數據請求,減少不必要的開銷。 .netcore項目實戰交流群(637326624),有興趣的朋友 ...
【.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
與作者聯繫吧。