【.NET Core項目實戰-統一認證平臺】第九章 授權篇-使用Dapper持久化IdentityServer4

来源:https://www.cnblogs.com/jackcao/archive/2018/12/03/10058274.html
-Advertisement-
Play Games

" 【.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;
        }
    }
}

整體框架基本確認了,現在就需要解決這裡用到的幾個配置信息和實現。

  1. DapperStoreOptions需要接收那些參數?

  2. 如何使用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信息,並介紹了實現過程,然後實現了SqlServerMysql兩種方式,也介紹了使用過程中遇到的技術問題,其實在實現過程中我發現的一個緩存和如何讓授權信息立即過期等問題,這塊大家可以一起先思考下如何實現,後續文章中我會介紹具體的實現方式,然後把緩存遷移到Redis里。

下一篇開始就正式介紹Ids4的幾種授權方式和具體的應用,以及如何在我們客戶端進行集成,如果在學習過程中遇到不懂或未理解的問題,歡迎大家加入QQ群聊637326624與作者聯繫吧。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. 小數據池, id() 小數據池針對的是: int, str, bool 在py文件中幾乎所有的字元串都會緩存. id() 查看變數的記憶體地址 2. is和==的區別 is 比較的是記憶體地址 == 比較的是內容 當兩個變數指向同一個對象的時候. is是True, ==也是True 3. 再談編碼 ...
  • 一、總覽 線程池類ThreadPoolExecutor的相關類需要先瞭解: (圖片來自:https://javadoop.com/post/java-thread-pool#%E6%80%BB%E8%A7%88) Executor:位於最頂層,只有一個 execute(Runnable runnab ...
  • 1.小數據池,id() 小數據池針對的是: int ,str,bool 都是不可變的數據類型 a.int 類型 a = 1000 b = 1000 print(id(a), id(b)) # 165830000 165830000 b. 字元串,如果單純的鞋字元串,幾乎都會被緩存 a = 1000 ...
  • 1. 小數據池, id() 小數據池針對的是: int, str, bool 在py文件中幾乎所有的字元串都會緩存. id() 查看變數的記憶體地址 2. is和==的區別 is 比較的是記憶體地址 == 比較的是內容 當兩個變數指向同一個對象的時候. is是True, ==也是True 3. 編碼 1 ...
  • 簡介 委托(Delegate):就是類似於C/C++中的函數指針,由於C 中沒有指針,使該語言存在著對某種方法的引用,該引用在運行時改變。被說成是:“委托可以把方法當作參數在另一個方法中傳遞和調用”,“委托是方法的快捷方式”等等,我的簡單理解就是創建兩個相同的函數,想用使用A函數,可以藉助委托函數B ...
  • List<Person> list=new List<Person>{ new Person(){Name="張三",Age=50,Address="重慶市沙坪壩區"}, new Person(){Name="李四",Age=20,Address="西科公寓"}, new Person(){Name ...
  • List<Person> list = new List<Person> { new Person{Name="張三",Age=20,Email="[email protected]"}, new Person{Name="李四",Age=30,Email="[email protected]"}, new Pers ...
  • 方法關鍵字: 交集:Intersect 差集:Except 並集:Union 使用代碼: 需註意:以上三個方法,只針對值類型的集合.如果數組是引用類型的對象集合,由於比較的是對象實例引用的地址,所以不能使用這些方法. ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...