当前位置: 移动技术网 > IT编程>开发语言>.net > 【.NET Core项目实战-统一认证平台】第九章 授权篇-使用Dapper持久化IdentityServer4

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

2018年12月04日  | 移动技术网IT编程  | 我要评论

二十八星宿传奇,湖北省委书记被杀,还魂门

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网