Ocelot(四)- 认证与授权 (3)

其实熟悉Postman的朋友可能就知道怎么一回事,Postman为了我们在使用过程中更加方便填入Token信息而单独列出了Authorization,实际上,最终还是会转换加入到请求头当中
这个请求头的Key就是Authorization,对应的值是Bearer + (空格) + Token。

Ocelot_032_identityserver_header

以上就是没有Ocelot网关时,IdentityServer的认证流程。

案例五 Ocelot集成IdentityServer服务

在上面的例子中,我是直接将下游服务暴露给客户端调用,当接入Ocelot网关时,我们要达到内外互隔的特性,于是就把IdentityServer服务也托管到Ocelot网关中,这样我们就能统一认证和服务请求时的入口。
于是,我们可以形成下面这个流程图:

Ocelot_033_identityserver_ocelot

根据流程图,我在Ocelot ReRoutes中添加两组路由

{ "DownstreamPathTemplate": "/connect/token", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8005 } ], "UpstreamPathTemplate": "/token", "UpstreamHttpMethod": [ "Post" ], "Priority": 2 }, { "DownstreamPathTemplate": "/api/ocelot/identityWilling", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 8001 } ], "UpstreamPathTemplate": "/ocelot/identityWilling", "UpstreamHttpMethod": [ "Get" ], "Priority": 2 }

第一组是将IdentityServer服务进行托管,这样客户端就可以直接通过Ocelot网关访问/token就可以进行认证,第二组是将下游服务进行托管

然后,也是按照之前例子的步骤,先通过:4727/token认证,然后将得到的Token以Bearer的方式加入到向下游服务的请求当中

Ocelot_034_identityserver_ocelottoken

Ocelot_035_identityserver_ocelotresult

结果也是跟我预想的是一致的,可以按照这样的流程进行身份认证。

但是!!!但是!!!但是!!!

当外面随便来一个人,跟前台说他要找我做一件事情,然后前台直接告诉他我的具体位置,就让他进公司找我了,然后当我接待他的时候,我才发现这个人根本就是来搞事的,拒绝他的请求。如果一天来这么几十号人,我还要不要正常干活了?

这明显就不符合实际应用场景,外面的人(客户端)在前台(Ocelot)的时候,就需要进行身份认证(IdentityServer),只有通过认证的人才能进公司(路由),我才会接触到这个人(响应),这才叫专人做专事。

于是,认证流程改为下图:

Ocelot_036_identityserver_ocelot2

准备下游服务

为了保证我的案例与上面这个认证流程是一致的,我就把前面在下游服务中的认证配置去掉。而且在实际生产环境中,客户端与下游服务的网络是隔断的,客户端只能通过网关的转发才能向下游服务发出请求。

OcelotDownAPI项目

public void ConfigureServices(IServiceCollection services) { //IdentityServerConfig identityServerConfig = new IdentityServerConfig(); //Configuration.Bind("IdentityServerConfig", identityServerConfig); //services.AddAuthentication(identityServerConfig.IdentityScheme) // .AddIdentityServerAuthentication(options => // { // options.RequireHttpsMetadata = false; // options.Authority = $"http://{identityServerConfig.IP}:{identityServerConfig.Port}"; // options.ApiName = identityServerConfig.ResourceName; // } // ); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //app.UseAuthentication(); app.UseMvc(); }

同时也把API接口中的[Authorize]属性去除。

然后将OcelotDownAPI项目重新打包,部署在8001、8002端口,作为两个独立的下游服务。

配置IdentityServer

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyywgs.html