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

【.NET Core项目实战-统一认证平台】开篇及目录索引

上篇文章介绍了IdentityServer4的源码分析的内容,让咱们知道了IdentityServer4的一些运行原理,这篇将介绍如何使用dapper来持久化Identityserver4,让咱们对IdentityServer4理解更透彻,并优化下数据请求,减小没必要要的开销。html

.netcore项目实战交流群(637326624),有兴趣的朋友能够在群里交流讨论。mysql

1、数据如何实现持久化

在进行数据持久化以前,咱们要了解Ids4是如何实现持久化的呢?Ids4默认是使用内存实现的IClientStore、IResourceStore、IPersistedGrantStore三个接口,对应的分别是InMemoryClientStore、InMemoryResourcesStore、InMemoryPersistedGrantStore三个方法,这显然达不到咱们持久化的需求,由于都是从内存里提取配置信息,因此咱们要作到Ids4配置信息持久化,就须要实现这三个接口,做为优秀的身份认证框架,确定已经帮咱们想到了这点啦,有个EFCore的持久化实现,GitHub地址https://github.com/IdentityServer/IdentityServer4.EntityFramework,是否是万事大吉了呢?拿来直接使用吧,使用确定是没有问题的,可是咱们要分析下实现的方式和数据库结构,便于后续使用dapper来持久化和扩展成任意数据库存储。git

下面以IClientStore接口接口为例,讲解下如何实现数据持久化的。他的方法就是经过clientId获取Client记录,乍一看很简单,不论是用内存或数据库均可以很简单实现。github

Task<Client> FindClientByIdAsync(string clientId);

要看这个接口实际用途,就能够直接查看这个接口被注入到哪些方法中,最简单的方式就是Ctrl+Fsql

,经过查找会发现,Client实体里有不少关联记录也会被用到,所以咱们在提取Client信息时须要提取他对应的关联实体,那若是是数据库持久化,那应该怎么提取呢?这里能够参考IdentityServer4.EntityFramework项目,咱们执行下客户端受权以下图所示,您会发现可以正确返回结果,可是这里执行了哪些SQL查询呢?
数据库

从EFCore实现中能够看出来,就一个简单的客户端查询语句,尽然执行了10次数据库查询操做(可使用SQL Server Profiler查看详细的SQL语句),这也是为何使用IdentityServer4获取受权信息时奇慢无比的缘由。c#

public Task<Client> FindClientByIdAsync(string clientId)
{
    var client = _context.Clients
        .Include(x => x.AllowedGrantTypes)
        .Include(x => x.RedirectUris)
        .Include(x => x.PostLogoutRedirectUris)
        .Include(x => x.AllowedScopes)
        .Include(x => x.ClientSecrets)
        .Include(x => x.Claims)
        .Include(x => x.IdentityProviderRestrictions)
        .Include(x => x.AllowedCorsOrigins)
        .Include(x => x.Properties)
        .FirstOrDefault(x => x.ClientId == clientId);
    var model = client?.ToModel();

    _logger.LogDebug("{clientId} found in database: {clientIdFound}", clientId, model != null);

    return Task.FromResult(model);
}

这确定不是实际生产环境中想要的结果,咱们但愿是尽可能一次链接查询到想要的结果。其余2个方法相似,就不一一介绍了,咱们须要使用dapper来持久化存储,减小对服务器查询的开销。后端

特别须要注意的是,在使用refresh_token时,有个有效期的问题,因此须要经过可配置的方式设置按期清除过时的受权信息,实现方式能够经过数据库做业、定时器、后台任务等,使用dapper持久化时也须要实现此方法。api

2、使用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>();

3、测试功能应用

在前面客户端受权中,咱们增长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语句。且按期清理任务也启动成功,会根据配置的参数来执行清理过时受权信息。

4、使用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实现已经完成,若是想用其余数据库实现,直接按照我写的方法扩展下便可。

5、总结及预告

本篇我介绍了如何使用Dapper来持久化Ids4信息,并介绍了实现过程,而后实现了SqlServerMysql两种方式,也介绍了使用过程当中遇到的技术问题,其实在实现过程当中我发现的一个缓存和如何让受权信息当即过时等问题,这块你们能够一块儿先思考下如何实现,后续文章中我会介绍具体的实现方式,而后把缓存迁移到Redis里。

下一篇开始就正式介绍Ids4的几种受权方式和具体的应用,以及如何在咱们客户端进行集成,若是在学习过程当中遇到不懂或未理解的问题,欢迎你们加入QQ群聊637326624与做者联系吧。

相关文章
相关标签/搜索