Consul+Ocelot+Polly在.NetCore中使用(.NET5)-Consul服务注册,服务发现

Consul+Ocelot+Polly在.NetCore中使用(.NET5)-网关Ocelot+Consul

Consul+Ocelot+Polly在.NetCore中使用(.NET5)-Ocelot+Polly缓存、限流、熔断、降级

微服务网关Ocelot加入IdentityServer4鉴权-.NetCore(.NET5)中使用

一、简介

描述:微服务网关中,需要对访问的接口进行身份校验后再转发请求,网关中鉴权的方式有很多种,这里介绍的是常用的IdentityServer4鉴权添加到Ocelot网关中,同时下游的服务也要做身份校验,

  防止请求绕过网关直接请求下游服务。

二、创建IdentityServer4项目

这里重点不是说IdentityServer4,所以这里建一个简单的示例项目。

1.创建一个Identity4.Api项目

引入NugGet包

  1. IdentityServer4
  2. IdentityServer4.Storage

这里用的都是4.1.2版本

2.在项目中创建一个config静态类

  1. /// <summary>
  2. /// 配置
  3. /// </summary>
  4. public class Config
  5. {
  6. /// <summary>
  7. /// 定义作用域
  8. /// </summary>
  9. public static IEnumerable<ApiScope> ApiScopes =>
  10. new ApiScope[]
  11. {
  12. new ApiScope("gatewayScope"),
  13. new ApiScope("scope2")
  14. };
  15.  
  16. public static IEnumerable<ApiResource> ApiResources =>
  17. new ApiResource[]
  18. {
  19.  
  20. new ApiResource("server1","服务1")
  21. {
  22. //4.x必须写
  23. Scopes = { "gatewayScope" }
  24. },
  25. };
  26.  
  27. public static IEnumerable<Client> Clients =>
  28. new Client[]
  29. {
  30. new Client
  31. {
  32. ClientId = "client_test",
  33. ClientName = "测试客户端",
  34.  
  35. AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
  36. ClientSecrets = { new Secret("secret_test".Sha256()) },
  37.  
  38. AllowedScopes = { "gatewayScope" }
  39. },
  40. };
  41.  
  42. /// <summary>
  43. /// 测试的账号和密码
  44. /// </summary>
  45. /// <returns></returns>
  46. public static List<TestUser> GetTestUsers()
  47. {
  48. return new List<TestUser>
  49. {
  50. new TestUser()
  51. {
  52. SubjectId = "1",
  53. Username = "test",
  54. Password = "123456"
  55. }
  56. };
  57. }
  58. }

3.在Startup.cs的ConfigureServices()方法中加入

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. #region 内存方式
  4. services.AddIdentityServer()
  5. .AddDeveloperSigningCredential()
  6. .AddInMemoryApiResources(Config.ApiResources)
  7. .AddInMemoryClients(Config.Clients)
  8. .AddInMemoryApiScopes(Config.ApiScopes) //4.x新加
  9. .AddTestUsers(Config.GetTestUsers());
  10. #endregion
  11. services.AddControllersWithViews();
  12. }

4.在Startup.cs的Configure()方法中加入

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/Home/Error");
  10. }
  11. app.UseStaticFiles();
  12. app.UseRouting();
  13. app.UseAuthorization();
  14. app.UseIdentityServer();
  15. app.UseEndpoints(endpoints =>
  16. {
  17. endpoints.MapControllerRoute(
  18. name: "default",
  19. pattern: "{controller=Home}/{action=Index}/{id?}");
  20. });
  21. }

到这里一个IdentitySever4的鉴权中心就建好了,运行起来,用Postman测试获取token。

token获取成功,说明IdentityServer4的鉴权中心没问题了。

三、Ocelot中加入IdentityServer4认证

Ocelot网关默认已经集成了Id4的,我们需要做的事情有:

1.在配置中加入IdentityServer4的信息,ocelog.json中加入

  1.  
  1. {
  2. "Routes": [
  3. {
  4. //转发到下游服务地址--url变量
  5. "DownstreamPathTemplate": "/api/{url}",
  6. //下游http协议
  7. "DownstreamScheme": "http",
  8. //负载方式,
  9. "LoadBalancerOptions": {
  10. "Type": "RoundRobin" // 轮询
  11. },
  12. //上游地址
  13. "UpstreamPathTemplate": "/T1/{url}", //网关地址--url变量 //冲突的还可以加权重Priority
  14. "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
  15. "UseServiceDisConvery": true, //使用服务发现
  16. "ServiceName": "api", //Consul服务名称
  17. //熔断设置,熔断器使用Polly
  18. "QoSOptions": {
  19. "ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
  20. "DurationOfBreak": 10000, // 熔断的时间10s,单位为ms
  21. "TimeoutValue": 5000 //单位ms,如果下游请求的处理时间超过多少则自动将请求设置为超时 默认90秒
  22. },
  23. //鉴权
  24. "AuthenticationOptions": {
  25. "AuthenticationProviderKey": "Bearer", //指定一个key
  26. "AllowedScopes": [ "gatewayScope" ] //id4的作用域名称
  27. }
  28. }
  29. ],
  30. "GlobalConfiguration": {
  31. //Ocelot应用对外地址
  32. "BaseUrl": "http://172.16.2.9:5200",
  33. "ServiceDiscoveryProvider": {
  34. //Consul地址
  35. "Host": "172.16.2.84",
  36. //Consul端口
  37. "Port": 8500,
  38. "Type": "Consul" //由Consul提供服务发现,每次请求Consul
  39. }
  40. }
  41. }

2.把Id4加入到IOC中

添加NuGet包

  1. IdentityServer4.AccessTokenValidation

Ocelot项目Startup.cs中的ConfigureServices()方法加上

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. var authenticationProviderKey = "Bearer"; //这个为上面配置里的key
  4. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  5. .AddIdentityServerAuthentication(authenticationProviderKey, options =>
  6. {
  7. options.Authority = "http://localhost:5000";//id4服务地址
  8. options.ApiName = "server1";//id4 api资源里的apiname
  9. options.RequireHttpsMetadata = false; //不使用https
  10. options.SupportedTokens = SupportedTokens.Both;
  11. });
  12. services.AddOcelot()
  13. .AddConsul()
  14. .AddPolly();
  15. }

  

到这里,Ocelot网关配置Id4就配好了。

3.测试验证

先测试加了Id4后,不带token访问下网关

可以看到,报了401,没权限访问,再试一下把上面id4取到的token带上访问。

发现可以访问成功了。这Ocelot中加入Id4校验就完成了。

四、下游服务加入IdentityServer4认证

为什么下游服务要加身份校验呢,因为请求可能绕过网关直接访问下游服务,没有验证就会出问题了。

1.配置

只需要在startup.cs中的ConfigureServices中加入上面的代码,去掉AuthenticationProviderKey

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddControllersWithViews();
  4. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  5. .AddIdentityServerAuthentication(options =>
  6. {
  7. options.Authority = "http://localhost:5000";//id4服务地址
  8. options.ApiName = "server1";//id4 api资源里的apiname
  9. options.RequireHttpsMetadata = false; //不使用https
  10. options.SupportedTokens = SupportedTokens.Both;
  11. });
  12. services.AddControllers().AddJsonOptions(cfg =>
  13. {
  14. cfg.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  15. });
  16.  
  17. services.AddSingleton<OrderService>();
  18.  
  19. }

然后在Configure()方法中,    app.UseRouting();后面加上  app.UseAuthentication();

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/Home/Error");
  10. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  11. app.UseHsts();
  12. }
  13. app.UseHttpsRedirection();
  14. app.UseStaticFiles();
  15.  
  16. app.UseRouting();
  17. app.UseAuthentication();
  18. app.UseAuthorization();
  19.  
  20. app.UseEndpoints(endpoints =>
  21. {
  22. endpoints.MapControllerRoute(
  23. name: "default",
  24. pattern: "{controller=Home}/{action=Index}/{id?}");
  25. });
  26. //Consul注册
  27. app.UseConsul(Configuration);
  28. }

然后在要校验的地方加上[Authorize]

2.校验不带token直接访问下游服务

  

显示没权限,再试带上token直接访问下游服务。

很好,成功访问,然后再试下通过网关访问是否能正常访问。

也成了,全部配置完成!

源码地址:https://github.com/weixiaolong325/Ocelot-Consul-Polly-Id4.Demo

微服务网关Ocelot加入IdentityServer4鉴权-.NetCore(.NET5)中使用的更多相关文章

  1. 解决微服务网关Ocelot使用AddStoreOcelotConfigurationInConsul后请求404问题

    一个小插曲,最近研究 netcore 微服务网关,在使用AddStoreOcelotConfigurationInConsul将配置存到consul后,任何经过网关的请求都出现404,并且没有任何有用 ...

  2. 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  3. 服务网关Ocelot 入门Demo系列(01-Ocelot极简单Demo及负载均衡的配置)

    [前言] Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由.请求聚合.服务发现.认证.鉴权.限流熔断.并内置了负载均衡器与Service Fabric.Butt ...

  4. 小D课堂 - 新版本微服务springcloud+Docker教程_6-01 微服务网关介绍和使用场景

    笔记 第六章 微服务网关zuul开发实战 1.微服务网关介绍和使用场景     简介:讲解网关的作用和使用场景 (画图)          1)什么是网关         API Gateway,是系 ...

  5. 畅购商城(八):微服务网关和JWT令牌

    好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/RobodLee/DayDayUP,欢迎Star,更多文章请前往:目录导航 畅购商城(一):环境搭建 畅购商 ...

  6. .net core中使用Bumblebee架设微服务网关

    Bumblebee是款基于.net core开发开源的http服务网关,经过最近版本的完善在功能足以满足作为微服务网关的需要.在微服务网关功能中它提供了应用服务负载,故障迁移,安全控制,监控跟踪和日志 ...

  7. Bumblebee微服务网关的部署和扩展

    Bumblebee是.netcore下开源基于BeetleX.FastHttpApi扩展的HTTP微服务网关组件,它的主要作用是针对WebAPI集群服务作一个集中的转发和管理:作为应用网关它提供了应用 ...

  8. 微服务-网关-node.js by 大雄daysn

    目录 序言 一.node.js入门1.1 下载并安装1.2 从helloworld到一个web应用1.3 Express框架二.node.js搭建网关 三.node.js集群搭建   序言 首先一个问 ...

  9. 使用 Node.js 搭建微服务网关

    目录 Node.js 是什么 安装 node.js Node.js 入门 Node.js 应用场景 npm 镜像 使用 Node.js 搭建微服务网关 什么是微服务架构 使用 Node.js 实现反向 ...

随机推荐

  1. Three.js 中 相机的常用参数含义

    Three.js 中相机常用的参数有up.position和lookAt. position是指相机所在的位置,将人头比作相机的话,那么position就是人头的中心的位置: up类似于人的脖子可以调 ...

  2. python 动图gif合成与分解

    合成 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import imageio def main(imgs_ ...

  3. uniapp 设置背景图片

    uniapp 由于其特殊机制,导致了背景图片不能引用本地图片.只能通过 转成 base64 来进行设置 附上链接:https://oktools.net/image2base64 图片转成base64 ...

  4. SQLServer数据库查询语法

    SQLServer数据库查询语法 前言: SQLServer数据库介绍: SQLServer数据库是微软公司推出的一款关系型数据库系统,SQL Server是一个可扩展的.高性能的.为分布式客户机/服 ...

  5. Appium自动化(11) - 详解 Applications 类里的方法和源码解析

    如果你还想从头学起Appium,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1693896.html 前言 Applications 类 ...

  6. MongoDB(2)- 安装 MongoDB

    MacOS 安装 MongoDB 博主目前都用 mac 电脑练习,所以这里重点讲 MacOS 安装方式 系统要求 MongoDB 4.4 社区版支持 macOS 10.13 或更高版本 安装 Home ...

  7. python3 爬虫五大模块之五:信息采集器

    Python的爬虫框架主要可以分为以下五个部分: 爬虫调度器:用于各个模块之间的通信,可以理解为爬虫的入口与核心(main函数),爬虫的执行策略在此模块进行定义: URL管理器:负责URL的管理,包括 ...

  8. JS004. 获取数组最后一个元素且不改变数组的四种方法

    TAG: Array.length Array.prototype.reverse() Array.prototype.slice() Array.prototype.pop() Array对象 - ...

  9. weblogic漏洞分析之CVE-2017-3248 & CVE-2018-2628

    CVE-2017-3248 & CVE-2018-2628 后面的漏洞就是2017-3248的绕过而已,所以poc都一样,只是使用的payload不同 本机开启JRMP服务端 ->利用T ...

  10. CentOS获取公网IP

    Curl 纯文本格式输出: curl icanhazip.com curl ifconfig.me curl curlmyip.com curl ip.appspot.com curl ipinfo. ...