• 【.NET Core项目实战-统一认证平台】第九章 授权篇-使用Dapper持久化IdentityServer4


    【.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与作者联系吧。

  • 相关阅读:
    【转】Java并发编程:深入剖析ThreadLocal
    【转】关于Java的Daemon线程的理解
    【转】详细分析Java中断机制
    【转】Java并发编程注意事项
    【转】Java并发编程:volatile关键字解析
    【转】Java并发编程:Lock
    【转】JVM运行原理及JVM中的Stack和Heap的实现过程
    【转】Linux常用命令大全
    Linux 命令学习
    js中的prototype和__proto__
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/11945309.html
Copyright © 2020-2023  润新知