博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【.NET Core项目实战-统一认证平台】第九章 授权篇-使用Dapper持久化IdentityServer4...
阅读量:5170 次
发布时间:2019-06-13

本文共 26845 字,大约阅读时间需要 89 分钟。

原文:

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

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

一、数据如何实现持久化

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

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

Task
FindClientByIdAsync(string clientId);

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

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

1529926-20181203142637556-807629900.png

从EFCore实现中可以看出来,就一个简单的客户端查询语句,尽然执行了10次数据库查询操作(可以使用SQL Server Profiler查看详细的SQL语句),这也是为什么使用IdentityServer4获取授权信息时奇慢无比的原因。

public Task
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{    ///     /// 金焰的世界    /// 2018-12-03    /// 使用Dapper扩展    ///     public static class IdentityServerDapperBuilderExtensions    {        ///         /// 配置Dapper接口和实现(默认使用SqlServer)        ///         /// The builder.        /// 存储配置信息        /// 
public static IIdentityServerBuilder AddDapperStore( this IIdentityServerBuilder builder, Action
storeOptionsAction = null) { var options = new DapperStoreOptions(); builder.Services.AddSingleton(options); storeOptionsAction?.Invoke(options); builder.Services.AddTransient
(); builder.Services.AddTransient
(); builder.Services.AddTransient
(); return builder; } ///
/// 使用Mysql存储 /// ///
///
public static IIdentityServerBuilder UseMySql(this IIdentityServerBuilder builder) { builder.Services.AddTransient
(); builder.Services.AddTransient
(); builder.Services.AddTransient
(); return builder; } }}

整体框架基本确认了,现在就需要解决这里用到的几个配置信息和实现。

  1. DapperStoreOptions需要接收那些参数?

  2. 如何使用dapper实现存储的三个接口信息?

首先我们定义下配置文件,用来接收数据库的连接字符串和配置清理的参数并设置默认值。

namespace IdentityServer4.Dapper.Options{    ///     /// 金焰的世界    /// 2018-12-03    /// 配置存储信息    ///     public class DapperStoreOptions    {        ///         /// 是否启用自定清理Token        ///         public bool EnableTokenCleanup { get; set; } = false;        ///         /// 清理token周期(单位秒),默认1小时        ///         public int TokenCleanupInterval { get; set; } = 3600;        ///         /// 连接字符串        ///         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{    ///     /// 金焰的世界    /// 2018-12-03    /// 实现提取客户端存储信息    ///     public class SqlServerClientStore: IClientStore    {        private readonly ILogger
_logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerClientStore(ILogger
logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } ///
/// 根据客户端ID 获取客户端信息内容 /// ///
///
public async Task
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
(); var ClientGrantTypes = multi.Read
(); var ClientRedirectUris = multi.Read
(); var ClientScopes = multi.Read
(); var ClientSecrets = multi.Read
(); 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{    ///     /// 金焰的世界    /// 2018-12-03    /// 客户端实体映射    ///     /// 
public class ClientMapperProfile : Profile { public ClientMapperProfile() { CreateMap
>() .ReverseMap(); CreateMap
() .ForMember(dest => dest.ProtocolType, opt => opt.Condition(srs => srs != null)) .ReverseMap(); CreateMap
() .ConstructUsing(src => src.Origin) .ReverseMap() .ForMember(dest => dest.Origin, opt => opt.MapFrom(src => src)); CreateMap
() .ConstructUsing(src => src.Provider) .ReverseMap() .ForMember(dest => dest.Provider, opt => opt.MapFrom(src => src)); CreateMap
(MemberList.None) .ConstructUsing(src => new Claim(src.Type, src.Value)) .ReverseMap(); CreateMap
() .ConstructUsing(src => src.Scope) .ReverseMap() .ForMember(dest => dest.Scope, opt => opt.MapFrom(src => src)); CreateMap
() .ConstructUsing(src => src.PostLogoutRedirectUri) .ReverseMap() .ForMember(dest => dest.PostLogoutRedirectUri, opt => opt.MapFrom(src => src)); CreateMap
() .ConstructUsing(src => src.RedirectUri) .ReverseMap() .ForMember(dest => dest.RedirectUri, opt => opt.MapFrom(src => src)); CreateMap
() .ConstructUsing(src => src.GrantType) .ReverseMap() .ForMember(dest => dest.GrantType, opt => opt.MapFrom(src => src)); CreateMap
(MemberList.Destination) .ForMember(dest => dest.Type, opt => opt.Condition(srs => srs != null)) .ReverseMap(); } }}
using AutoMapper;namespace IdentityServer4.Dapper.Mappers{    ///     /// 金焰的世界    /// 2018-12-03    /// 客户端信息映射    ///     public static class ClientMappers    {        static ClientMappers()        {            Mapper = new MapperConfiguration(cfg => cfg.AddProfile
()) .CreateMapper(); } internal static IMapper Mapper { get; } public static Models.Client ToModel(this Entities.Client entity) { return Mapper.Map
(entity); } public static Entities.Client ToEntity(this Models.Client model) { return Mapper.Map
(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{    ///     /// 金焰的世界    /// 2018-12-03    /// 重写资源存储方法    ///     public class SqlServerResourceStore : IResourceStore    {        private readonly ILogger
_logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerResourceStore(ILogger
logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } ///
/// 根据api名称获取相关信息 /// ///
///
public async Task
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
(); var ApiScopes = multi.Read
(); 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; } ///
/// 根据作用域信息获取接口资源 /// ///
///
public async Task
> FindApiResourcesByScopeAsync(IEnumerable
scopeNames) { var apiResourceData = new List
(); 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
(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
(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; } ///
/// 根据scope获取身份资源 /// ///
///
public async Task
> FindIdentityResourcesByScopeAsync(IEnumerable
scopeNames) { var apiResourceData = new List
(); 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
(sql))?.AsList(); if (data != null && data.Count > 0) { foreach (var model in data) { apiResourceData.Add(model.ToModel()); } } } return apiResourceData; } ///
/// 获取所有资源实现 /// ///
public async Task
GetAllResourcesAsync() { var apiResourceData = new List
(); var identityResourceData = new List
(); using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from IdentityResources where Enabled=1"; var data = (await connection.QueryAsync
(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
(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
(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{    ///     /// 金焰的世界    /// 2018-12-03    /// 重写授权信息存储    ///     public class SqlServerPersistedGrantStore : IPersistedGrantStore    {        private readonly ILogger
_logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerPersistedGrantStore(ILogger
logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } ///
/// 根据用户标识获取所有的授权信息 /// ///
用户标识 ///
public async Task
> GetAllAsync(string subjectId) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from PersistedGrants where SubjectId=@subjectId"; var data = (await connection.QueryAsync
(sql, new { subjectId }))?.AsList(); var model = data.Select(x => x.ToModel()); _logger.LogDebug("{persistedGrantCount} persisted grants found for {subjectId}", data.Count, subjectId); return model; } } ///
/// 根据key获取授权信息 /// ///
认证信息 ///
public async Task
GetAsync(string key) { using (var connection = new SqlConnection(_configurationStoreOptions.DbConnectionStrings)) { string sql = "select * from PersistedGrants where [Key]=@key"; var result = await connection.QueryFirstOrDefaultAsync
(sql, new { key }); var model = result.ToModel(); _logger.LogDebug("{persistedGrantKey} found in database: {persistedGrantKeyFound}", key, model != null); return model; } } ///
/// 根据用户标识和客户端ID移除所有的授权信息 /// ///
用户标识 ///
客户端ID ///
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); } } ///
/// 移除指定的标识、客户端、类型等授权信息 /// ///
标识 ///
客户端ID ///
授权类型 ///
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); } } ///
/// 移除指定KEY的授权信息 /// ///
///
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); } } ///
/// 存储授权信息 /// ///
实体 ///
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{    ///     /// 金焰的世界    /// 2018-12-03    /// 过期授权清理接口    ///     public interface IPersistedGrants    {        ///         /// 移除指定时间的过期信息        ///         /// 过期时间        /// 
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{    ///     /// 金焰的世界    /// 2018-12-03    /// 实现授权信息自定义管理    ///     public class SqlServerPersistedGrants : IPersistedGrants    {        private readonly ILogger
_logger; private readonly DapperStoreOptions _configurationStoreOptions; public SqlServerPersistedGrants(ILogger
logger, DapperStoreOptions configurationStoreOptions) { _logger = logger; _configurationStoreOptions = configurationStoreOptions; } ///
/// 移除指定的时间过期授权信息 /// ///
Utc时间 ///
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{    ///     /// 金焰的世界    /// 2018-12-03    /// 清理过期Token方法    ///     public class TokenCleanup    {        private readonly ILogger
_logger; private readonly DapperStoreOptions _options; private readonly IPersistedGrants _persistedGrants; private CancellationTokenSource _source; public TimeSpan CleanupInterval => TimeSpan.FromSeconds(_options.TokenCleanupInterval); public TokenCleanup(IPersistedGrants persistedGrants, ILogger
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{    ///     /// 金焰的世界    /// 2018-12-03    /// 授权后端清理服务    ///     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
(); builder.Services.AddSingleton
();

三、测试功能应用

在前面客户端授权中,我们增加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监控,查看运行代码。

1529926-20181203142711604-2115922153.png

访问能够得到我们预期的结果且查询全部是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();

1529926-20181203142729446-950825013.png

可以返回正确的结果数据,扩展Mysql实现已经完成,如果想用其他数据库实现,直接按照我写的方法扩展下即可。

五、总结及预告

本篇我介绍了如何使用Dapper来持久化Ids4信息,并介绍了实现过程,然后实现了SqlServerMysql两种方式,也介绍了使用过程中遇到的技术问题,其实在实现过程中我发现的一个缓存和如何让授权信息立即过期等问题,这块大家可以一起先思考下如何实现,后续文章中我会介绍具体的实现方式,然后把缓存迁移到Redis里。

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

posted on
2018-12-03 15:05 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/lonelyxmas/p/10058553.html

你可能感兴趣的文章
批量打渠道包
查看>>
修改系统文件内容的经典错误总结
查看>>
CodeForces Round #295 Div.2
查看>>
项目经理在项目各阶段的工作重点-更新版
查看>>
数据库链接池c3p0配置踩坑
查看>>
Java多线程和并发(一),进程与线程的区别
查看>>
使用xftp无法连接阿里云服务器 或者linux
查看>>
js高级(部分)
查看>>
【BZOJ4566】[Haoi2016]找相同字符 后缀数组+单调栈
查看>>
【BZOJ4200】[Noi2015]小园丁与老司机 DP+最小流
查看>>
【BZOJ2959】长跑 LCT+并查集
查看>>
python之MD5加密
查看>>
Elasticsearch-sql 用SQL查询Elasticsearch
查看>>
HTML超连接(a标记)
查看>>
servlet学习笔记_2
查看>>
cf(415 A,B)
查看>>
linux压缩和解压缩命令大全
查看>>
Sublime text 3 注册码激活码 版本号3143
查看>>
通过wifi无法连接手机调试
查看>>
HD 2177(威佐夫博弈 入门)
查看>>