【.NET Core项目实战-统一认证平台】第六章 网关篇-自定义客户端授权
【.net core项目实战-统一认证平台】开篇及目录索引
上篇文章我们介绍了网关使用
redis
进行缓存,并介绍了如何进行缓存实现,缓存信息清理接口的使用。本篇我们将介绍如何实现网关自定义客户端授权,实现可以为不同的接入客户端设置不同的访问权限。.netcore项目实战交流群(637326624),有兴趣的朋友可以在群里交流讨论。
一、功能描述
网关重点功能之一鉴权,需要实现对不同的客户端进行授权访问,禁止访问未经授权的路由地址,且需要对无权访问的请求,返回通用的格式。
比如网关有1-10个可用路由,客户端a只能访问1-5,客户端b只能访问6-10,这时我们就无法通过ocelot
配置授权来进行自定义认证,这块就需要我们增加自定义的认证管道来实现功能,尽量不影响网关已有的功能。
下面我们就该功能如何实现展开讲解,希望大家先理解下功能需求,然后在延伸到具体实现。
二、数据库设计
我在中讲解了我们网关配置信息设计,本篇将在那个基础上增加客户端认证需要用到的表的相关设计,设计客户端授权结构如下。其中客户端使用的identityserver4
客户端表结构。
设计好概念模型后,我们生成物理模型,然后生成数据库脚本。
设计思想为可以添加自定义的授权组,为每一个授权分配能够访问的路由,然后为网关授权的客户端分配一个或多个授权组,每次客户端请求时,如果路由设置了授权访问,就校验客户端是否存在路由访问权限,如果无访问权限,直接返回401未授权提醒。
感觉是不是很简单呢?有了这个自定义的客户端认证,那么我们后端服务可以专注于自己的业务逻辑而无需再过多了进行权限处理了。
三、功能实现
1、功能开启配置
网关应该支持自定义客户端授权中间件是否启用,因为一些小型项目是不需要对每个客户端进行单独授权的,中型和大型项目才有可能遇到自定义配置情况,所以我们需要在配置文件增加配置选项。在ahphocelotconfiguration.cs
配置类中增加属性,默认不开启,而且需要知道客户端标识名称。
/// <summary> /// 金焰的世界 /// 2018-11-15 /// 是否启用客户端授权,默认不开启 /// </summary> public bool clientauthorization { get; set; } = false; /// <summary> /// 金焰的世界 /// 2018-11-15 /// 客户端授权缓存时间,默认30分钟 /// </summary> public int clientauthorizationcachetime { get; set; } = 1800; /// <summary> /// 金焰的世界 /// 2018-11-15 /// 客户端标识,默认 client_id /// </summary> public string clientkey { get; set; } = "client_id";
那我们如何把自定义的授权增加到网关流程里呢?这块我们就需要订制自己的授权中间件。
2、实现客户端授权中间件
首先我们定义一个自定义授权中间件ahphauthenticationmiddleware
,需要继承ocelotmiddleware
,然后我们要实现invoke
方法,详细代码如下。
using ctr.ahphocelot.configuration; using microsoft.aspnetcore.http; using ocelot.configuration; using ocelot.logging; using ocelot.middleware; using system; using system.collections.generic; using system.linq; using system.net; using system.text; using system.threading.tasks; namespace ctr.ahphocelot.authentication.middleware { /// <summary> /// 金焰的世界 /// 2018-11-15 /// 自定义授权中间件 /// </summary> public class ahphauthenticationmiddleware : ocelotmiddleware { private readonly ocelotrequestdelegate _next; private readonly ahphocelotconfiguration _options; private readonly iahphauthenticationprocessor _ahphauthenticationprocessor; public ahphauthenticationmiddleware(ocelotrequestdelegate next, iocelotloggerfactory loggerfactory, iahphauthenticationprocessor ahphauthenticationprocessor, ahphocelotconfiguration options) : base(loggerfactory.createlogger<ahphauthenticationmiddleware>()) { _next = next; _ahphauthenticationprocessor = ahphauthenticationprocessor; _options = options; } public async task invoke(downstreamcontext context) { if (!context.iserror && context.httpcontext.request.method.toupper() != "options" && isauthenticatedroute(context.downstreamreroute)) { if (!_options.clientauthorization) { logger.loginformation($"未启用客户端授权管道"); await _next.invoke(context); } else { logger.loginformation($"{context.httpcontext.request.path} 是认证路由. {middlewarename} 开始校验授权信息"); #region 提取客户端id var clientid = "client_cjy"; var path = context.downstreamreroute.upstreampathtemplate.originalvalue; //路由地址 var clientclaim = context.httpcontext.user.claims.firstordefault(p => p.type == _options.clientkey); if (!string.isnullorempty(clientclaim?.value)) {//从claims中提取客户端id clientid = clientclaim?.value; } #endregion if (await _ahphauthenticationprocessor.checkclientauthenticationasync(clientid, path)) { await _next.invoke(context); } else {//未授权直接返回错误 var errresult = new errorresult() { errcode=401, errmsg= "请求地址未授权" }; var message = errresult.tojson(); context.httpcontext.response.statuscode = (int)httpstatuscode.ok; await context.httpcontext.response.writeasync(message); return; } } } else { await _next.invoke(context); } } private static bool isauthenticatedroute(downstreamreroute reroute) { return reroute.isauthenticated; } } }
有了这个中间件,那么如何添加到ocelot的管道里呢?这里就需要查看ocelot源代码了,看是如何实现管道调用的,ocelotmiddlewareextensions
实现管道部分如下,buildocelotpipeline
里具体的流程。其实我在之前的ocelot源码解读里也讲解过原理了,奈斯,既然找到了,那么我们就加入我们自定义的授权中间件即可。
public static async task<iapplicationbuilder> useocelot(this iapplicationbuilder builder, ocelotpipelineconfiguration pipelineconfiguration) { var configuration = await createconfiguration(builder); configurediagnosticlistener(builder); return createocelotpipeline(builder, pipelineconfiguration); } private static iapplicationbuilder createocelotpipeline(iapplicationbuilder builder, ocelotpipelineconfiguration pipelineconfiguration) { var pipelinebuilder = new ocelotpipelinebuilder(builder.applicationservices); pipelinebuilder.buildocelotpipeline(pipelineconfiguration); var firstdelegate = pipelinebuilder.build(); /* inject first delegate into first piece of asp.net middleware..maybe not like this then because we are updating the http context in ocelot it comes out correct for rest of asp.net.. */ builder.properties["analysis.nextmiddlewarename"] = "transitiontoocelotmiddleware"; builder.use(async (context, task) => { var downstreamcontext = new downstreamcontext(context); await firstdelegate.invoke(downstreamcontext); }); return builder; }
添加使用自定义授权中间件扩展ahphauthenticationmiddlewareextensions
,代码如下。
using ocelot.middleware.pipeline; using system; using system.collections.generic; using system.text; namespace ctr.ahphocelot.authentication.middleware { /// <summary> /// 金焰的世界 /// 2018-11-15 /// 使用自定义授权中间件 /// </summary> public static class ahphauthenticationmiddlewareextensions { public static iocelotpipelinebuilder useahphauthenticationmiddleware(this iocelotpipelinebuilder builder) { return builder.usemiddleware<ahphauthenticationmiddleware>(); } } }
有了这个中间件扩展后,我们就在管道的合适地方加入我们自定义的中间件。我们添加我们自定义的管道扩展ocelotpipelineextensions
,然后把自定义授权中间件加入到认证之后。
using system; using system.threading.tasks; using ctr.ahphocelot.authentication.middleware; using ocelot.authentication.middleware; using ocelot.authorisation.middleware; using ocelot.cache.middleware; using ocelot.claims.middleware; using ocelot.downstreamroutefinder.middleware; using ocelot.downstreamurlcreator.middleware; using ocelot.errors.middleware; using ocelot.headers.middleware; using ocelot.loadbalancer.middleware; using ocelot.middleware; using ocelot.middleware.pipeline; using ocelot.querystrings.middleware; using ocelot.ratelimit.middleware; using ocelot.request.middleware; using ocelot.requester.middleware; using ocelot.requestid.middleware; using ocelot.responder.middleware; using ocelot.websockets.middleware; namespace ctr.ahphocelot.middleware { /// <summary> /// 金焰的世界 /// 2018-11-15 /// 网关管道扩展 /// </summary> public static class ocelotpipelineextensions { public static ocelotrequestdelegate buildahphocelotpipeline(this iocelotpipelinebuilder builder, ocelotpipelineconfiguration pipelineconfiguration) { // this is registered to catch any global exceptions that are not handled // it also sets the request id if anything is set globally builder.useexceptionhandlermiddleware(); // if the request is for websockets upgrade we fork into a different pipeline builder.mapwhen(context => context.httpcontext.websockets.iswebsocketrequest, app => { app.usedownstreamroutefindermiddleware(); app.usedownstreamrequestinitialiser(); app.useloadbalancingmiddleware(); app.usedownstreamurlcreatormiddleware(); app.usewebsocketsproxymiddleware(); }); // allow the user to respond with absolutely anything they want. builder.useifnotnull(pipelineconfiguration.preerrorrespondermiddleware); // this is registered first so it can catch any errors and issue an appropriate response builder.userespondermiddleware(); // then we get the downstream route information builder.usedownstreamroutefindermiddleware(); //expand other branch pipes if (pipelineconfiguration.mapwhenocelotpipeline != null) { foreach (var pipeline in pipelineconfiguration.mapwhenocelotpipeline) { builder.mapwhen(pipeline); } } // now we have the ds route we can transform headers and stuff? builder.usehttpheaderstransformationmiddleware(); // initialises downstream request builder.usedownstreamrequestinitialiser(); // we check whether the request is ratelimit, and if there is no continue processing builder.useratelimiting(); // this adds or updates the request id (initally we try and set this based on global config in the error handling middleware) // if anything was set at global level and we have a different setting at re route level the global stuff will be overwritten // this means you can get a scenario where you have a different request id from the first piece of middleware to the request id middleware. builder.userequestidmiddleware(); // allow pre authentication logic. the idea being people might want to run something custom before what is built in. builder.useifnotnull(pipelineconfiguration.preauthenticationmiddleware); // now we know where the client is going to go we can authenticate them. // we allow the ocelot middleware to be overriden by whatever the // user wants if (pipelineconfiguration.authenticationmiddleware == null) { builder.useauthenticationmiddleware(); } else { builder.use(pipelineconfiguration.authenticationmiddleware); } //添加自定义授权中间 2018-11-15 金焰的世界 builder.useahphauthenticationmiddleware(); // allow pre authorisation logic. the idea being people might want to run something custom before what is built in. builder.useifnotnull(pipelineconfiguration.preauthorisationmiddleware); // now we have authenticated and done any claims transformation we // can authorise the request // we allow the ocelot middleware to be overriden by whatever the // user wants if (pipelineconfiguration.authorisationmiddleware == null) { builder.useauthorisationmiddleware(); } else { builder.use(pipelineconfiguration.authorisationmiddleware); } // allow the user to implement their own query string manipulation logic builder.useifnotnull(pipelineconfiguration.prequerystringbuildermiddleware); // get the load balancer for this request builder.useloadbalancingmiddleware(); // this takes the downstream route we retrieved earlier and replaces any placeholders with the variables that should be used builder.usedownstreamurlcreatormiddleware(); // not sure if this is the best place for this but we use the downstream url // as the basis for our cache key. builder.useoutputcachemiddleware(); //we fire off the request and set the response on the scoped data repo builder.usehttprequestermiddleware(); return builder.build(); } private static void useifnotnull(this iocelotpipelinebuilder builder, func<downstreamcontext, func<task>, task> middleware) { if (middleware != null) { builder.use(middleware); } } } }
有了这个自定义的管道扩展后,我们需要应用到网关启动里,修改我们创建管道的方法如下。
private static iapplicationbuilder createocelotpipeline(iapplicationbuilder builder, ocelotpipelineconfiguration pipelineconfiguration) { var pipelinebuilder = new ocelotpipelinebuilder(builder.applicationservices); //pipelinebuilder.buildocelotpipeline(pipelineconfiguration); //使用自定义管道扩展 2018-11-15 金焰的世界 pipelinebuilder.buildahphocelotpipeline(pipelineconfiguration); var firstdelegate = pipelinebuilder.build(); /* inject first delegate into first piece of asp.net middleware..maybe not like this then because we are updating the http context in ocelot it comes out correct for rest of asp.net.. */ builder.properties["analysis.nextmiddlewarename"] = "transitiontoocelotmiddleware"; builder.use(async (context, task) => { var downstreamcontext = new downstreamcontext(context); await firstdelegate.invoke(downstreamcontext); }); return builder; }
现在我们完成了网关的扩展和应用,但是是否注意到了,我们的网关接口还未实现呢?什么接口呢?
iahphauthenticationprocessor
这个接口虽然定义了,但是一直未实现,现在开始我们要实现下这个接口,我们回看下我们使用这个接口的什么方法,就是检查客户端是否有访问路由的权限。
3、结合数据库实现校验及缓存
每次请求都需要校验客户端是否授权,如果不缓存此热点数据,那么对网关开销很大,所以我们需要增加缓存。
新建ahphauthenticationprocessor
类来实现认证接口,代码如下。
using ctr.ahphocelot.configuration; using ocelot.cache; using system; using system.collections.generic; using system.text; using system.threading.tasks; namespace ctr.ahphocelot.authentication { /// <summary> /// 金焰的世界 /// 2018-11-15 /// 实现自定义授权处理器逻辑 /// </summary> public class ahphauthenticationprocessor : iahphauthenticationprocessor { private readonly iclientauthenticationrepository _clientauthenticationrepository; private readonly ahphocelotconfiguration _options; private readonly iocelotcache<clientrolemodel> _ocelotcache; public ahphauthenticationprocessor(iclientauthenticationrepository clientauthenticationrepository, ahphocelotconfiguration options, iocelotcache<clientrolemodel> ocelotcache) { _clientauthenticationrepository = clientauthenticationrepository; _options = options; _ocelotcache = ocelotcache; } /// <summary> /// 校验当前的请求地址客户端是否有权限访问 /// </summary> /// <param name="clientid">客户端id</param> /// <param name="path">请求地址</param> /// <returns></returns> public async task<bool> checkclientauthenticationasync(string clientid, string path) { var enableprefix = _options.rediskeyprefix + "clientauthentication"; var key = ahphocelothelper.computecounterkey(enableprefix, clientid, "", path); var cacheresult = _ocelotcache.get(key, enableprefix); if (cacheresult!=null) {//提取缓存数据 return cacheresult.role; } else {//重新获取认证信息 var result = await _clientauthenticationrepository.clientauthenticationasync(clientid, path); //添加到缓存里 _ocelotcache.add(key, new clientrolemodel() { cachetime = datetime.now,role=result }, timespan.fromminutes(_options.clientauthorizationcachetime), enableprefix); return result; } } } }
代码很简单,就是从缓存中查找看是否有数据,如果存在直接返回,如果不存在,就从仓储中提取访问权限,然后写入缓存,写入缓存的时间可由配置文件写入,默认为30分钟,可自行根据业务需要修改。
现在我们还需要解决2个问题,这个中间件才能正常运行,第一iclientauthenticationrepository
接口未实现和注入;第二iocelotcache<clientrolemodel>
未注入,那我们接下来实现这两块,然后就可以测试我们第一个中间件啦。
新建sqlserverclientauthenticationrepository
类,来实现iclientauthenticationrepository
接口,实现代码如下。
using ctr.ahphocelot.authentication; using ctr.ahphocelot.configuration; using system; using system.collections.generic; using system.data.sqlclient; using system.text; using system.threading.tasks; using dapper; namespace ctr.ahphocelot.database.sqlserver { /// <summary> /// 金焰的世界 /// 2018-11-16 /// 使用sqlserver实现客户端授权仓储 /// </summary> public class sqlserverclientauthenticationrepository : iclientauthenticationrepository { private readonly ahphocelotconfiguration _option; public sqlserverclientauthenticationrepository(ahphocelotconfiguration option) { _option = option; } /// <summary> /// 校验获取客户端是否有访问权限 /// </summary> /// <param name="clientid">客户端id</param> /// <param name="path">请求路由</param> /// <returns></returns> public async task<bool> clientauthenticationasync(string clientid, string path) { using (var connection = new sqlconnection(_option.dbconnectionstrings)) { string sql = @"select count(1) from ahphclients t1 inner join ahphclientgroup t2 on t1.id=t2.id inner join ahphauthgroup t3 on t2.groupid = t3.groupid inner join ahphreroutegroupauth t4 on t3.groupid = t4.groupid inner join ahphreroute t5 on t4.rerouteid = t5.rerouteid where enabled = 1 and clientid = @clientid and t5.infostatus = 1 and upstreampathtemplate = @path"; var result= await connection.queryfirstordefaultasync<int>(sql, new { clientid = clientid, path = path }); return result > 0; } } } }
现在需要注入下实现,这块应该都知道在哪里加入了吧?没错servicecollectionextensions
扩展又用到啦,现在梳理下流程感觉是不是很清晰呢?
builder.services.addsingleton<iclientauthenticationrepository, sqlserverclientauthenticationrepository>(); builder.services.addsingleton<iahphauthenticationprocessor, ahphauthenticationprocessor>();
再添加缓存的注入实现,到此我们的第一个中间件全部添加完毕了,现在可以开始测试我们的中间件啦。
builder.services.addsingleton<iocelotcache<clientrolemodel>, inrediscache<clientrolemodel>>();
4、测试授权中间件
我们先在数据库插入客户端授权脚本,脚本如下。
--插入测试客户端 insert into ahphclients(clientid,clientname) values('client1','测试客户端1') insert into ahphclients(clientid,clientname) values('client2','测试客户端2') --插入测试授权组 insert into ahphauthgroup values('授权组1','只能访问/cjy/values路由',1); insert into ahphauthgroup values('授权组2','能访问所有路由',1); --插入测试组权限 insert into ahphreroutegroupauth values(1,1); insert into ahphreroutegroupauth values(2,1); insert into ahphreroutegroupauth values(2,2); --插入客户端授权 insert into ahphclientgroup values(1,1); insert into ahphclientgroup values(2,2); --设置测试路由只有授权才能访问 update ahphreroute set authenticationoptions='{"authenticationproviderkey": "testkey"}' where rerouteid in(1,2);
这块设置了客户端2可以访问路由/cjy/values
,客户端1可以访问路由/cjy/values 和 /ctr/values/{id}
,开始使用postman
来测试这个中间件看是否跟我设置的一毛一样,各种dotnet run
启动吧。启动前别忘了在我们网关配置文件里,设置启动客户端授权 option.clientauthorization = true;
,是不是很简单呢?
为了测试授权效果,我们需要把网关项目增加认证,详细看代码,里面就是定义了授权认证,启动我们默认的认证地址。
var authenticationproviderkey = "testkey"; action<identityserverauthenticationoptions> gatewayoptions = o => { o.authority = "http://localhost:6611"; o.apiname = "gateway"; o.requirehttpsmetadata = false; }; services.addauthentication() .addidentityserverauthentication(authenticationproviderkey, gatewayoptions);
测试结果如下,达到我们预期目的。
终于完成了我们的自定义客户端授权啦,此处应该掌声不断。
5、增加mysql支持
看过我前面的文章应该知道,支持mysql
太简单啦,直接重写iclientauthenticationrepository
实现,然后注入到usemysql
里,问题就解决啦。感觉是不是不可思议,这就是.netcore
的魅力,简单到我感觉到我再贴代码就是侮辱智商一样。
6、重构认证失败输出,保持与ocelot一致风格
前面我们定义了未授权使用自定义的clientrolemodel
输出,最后发现这样太不优雅啦,我们需要简单重构下,来保持与ocelot
默认管道一致风格,修改代码如下。
//var errresult = new errorresult() { errcode=401, errmsg= "请求地址未授权" }; //var message = errresult.tojson(); //context.httpcontext.response.statuscode = (int)httpstatuscode.ok; //await context.httpcontext.response.writeasync(message); //return; var error = new unauthenticatederror($"请求认证路由 {context.httpcontext.request.path}客户端未授权"); logger.logwarning($"路由地址 {context.httpcontext.request.path} 自定义认证管道校验失败. {error}"); setpipelineerror(context, error);
再测试下未授权,返回状态为401,强迫症患者表示舒服多了。
四、总结及预告
本篇我们讲解的是网关如何实现自定义客户端授权功能,从设计到实现一步一步详细讲解,虽然只用一篇就写完了,但是涉及的知识点还是非常多的,希望大家认真理解实现的思想,看我是如何从规划到实现的,为了更好的帮助大家理解,从本篇开始,我的源代码都是一个星期以后再开源,大家可以根据博客内容自己手动实现下,有利于消化,如果在操作中遇到什么问题,可以加.net core项目实战交流群(qq群号:637326624)
咨询作者。
下一篇开始讲解自定义客户端限流,在学习下篇前可以自己先了解下限流相关内容,然后自己试着实现看看,带着问题学习可能事半功倍哦。
上一篇: .Net Core与跨平台时区
下一篇: 《西部世界》式的AI会有多危险?
推荐阅读
-
【.NET Core项目实战-统一认证平台】第二章网关篇-重构Ocelot来满足需求
-
【.NET Core项目实战-统一认证平台】第十六章 网关篇-Ocelot集成RPC服务
-
【.NET Core项目实战-统一认证平台】第九章 授权篇-使用Dapper持久化IdentityServer4
-
【.NET Core项目实战-统一认证平台】第十二章 授权篇-深入理解JWT生成及验证流程
-
【.NET Core项目实战-统一认证平台】第三章 网关篇-数据库存储配置(1)
-
【.NET Core项目实战-统一认证平台】第六章 网关篇-自定义客户端授权
-
【.NET Core项目实战-统一认证平台】第十三章 授权篇-如何强制有效令牌过期
-
【.NET Core项目实战-统一认证平台】第十四章 授权篇-自定义授权方式
-
【.NET Core项目实战-统一认证平台】第十五章 网关篇-使用二级缓存提升性能
-
【.NET Core项目实战-统一认证平台】第十章 授权篇-客户端授权