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包

IdentityServer4
IdentityServer4.Storage

这里用的都是4.1.2版本

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

 /// <summary>
/// 配置
/// </summary>
public class Config
{
/// <summary>
/// 定义作用域
/// </summary>
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("gatewayScope"),
new ApiScope("scope2")
}; public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{ new ApiResource("server1","服务1")
{
//4.x必须写
Scopes = { "gatewayScope" }
},
}; public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "client_test",
ClientName = "测试客户端", AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
ClientSecrets = { new Secret("secret_test".Sha256()) }, AllowedScopes = { "gatewayScope" }
},
}; /// <summary>
/// 测试的账号和密码
/// </summary>
/// <returns></returns>
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>
{
new TestUser()
{
SubjectId = "1",
Username = "test",
Password = "123456"
}
};
}
}

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

 public void ConfigureServices(IServiceCollection services)
{
#region 内存方式
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.ApiResources)
.AddInMemoryClients(Config.Clients)
.AddInMemoryApiScopes(Config.ApiScopes) //4.x新加
.AddTestUsers(Config.GetTestUsers());
#endregion
services.AddControllersWithViews();
}

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

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

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

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

三、Ocelot中加入IdentityServer4认证

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

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


{
"Routes": [
{
//转发到下游服务地址--url变量
"DownstreamPathTemplate": "/api/{url}",
//下游http协议
"DownstreamScheme": "http",
//负载方式,
"LoadBalancerOptions": {
"Type": "RoundRobin" // 轮询
},
//上游地址
"UpstreamPathTemplate": "/T1/{url}", //网关地址--url变量 //冲突的还可以加权重Priority
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"UseServiceDisConvery": true, //使用服务发现
"ServiceName": "api", //Consul服务名称
//熔断设置,熔断器使用Polly
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
"DurationOfBreak": 10000, // 熔断的时间10s,单位为ms
"TimeoutValue": 5000 //单位ms,如果下游请求的处理时间超过多少则自动将请求设置为超时 默认90秒
},
//鉴权
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer", //指定一个key
"AllowedScopes": [ "gatewayScope" ] //id4的作用域名称
}
}
],
"GlobalConfiguration": {
//Ocelot应用对外地址
"BaseUrl": "http://172.16.2.9:5200",
"ServiceDiscoveryProvider": {
//Consul地址
"Host": "172.16.2.84",
//Consul端口
"Port": 8500,
"Type": "Consul" //由Consul提供服务发现,每次请求Consul
}
}
}

2.把Id4加入到IOC中

添加NuGet包

IdentityServer4.AccessTokenValidation

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

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

  

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

3.测试验证

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

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

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

四、下游服务加入IdentityServer4认证

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

1.配置

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

 public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";//id4服务地址
options.ApiName = "server1";//id4 api资源里的apiname
options.RequireHttpsMetadata = false; //不使用https
options.SupportedTokens = SupportedTokens.Both;
});
services.AddControllers().AddJsonOptions(cfg =>
{
cfg.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
}); services.AddSingleton<OrderService>(); }

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

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
//Consul注册
app.UseConsul(Configuration);
}

然后在要校验的地方加上[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. 哦?原来这就是 JVM 垃圾!

    大家都知道,JVM 有垃圾回收的机制,垃圾回收的前提是要知道:什么是垃圾!然后再是如何识别垃圾! 什么是垃圾 垃圾,本质上就是没有引用的对象(们),下面来介绍两种垃圾 1. 没有引用指向的对象 下图是 ...

  2. 性能测试必备命令(3)- lscpu

    性能测试必备的 Linux 命令系列,可以看下面链接的文章哦 https://www.cnblogs.com/poloyy/category/1819490.html 介绍 显示有关CPU架构的信息 ...

  3. Golang入门学习(二):控制分支

    文章目录 @[TOC] 1. 控制分支 1.1 if-else分支 1.2 switch分支 1.4 while 和do...while循环结构 1.5 多种循环结构 1.6 break 1.7 co ...

  4. MySQL MHA高可用集群部署及故障切换

    一.MHA概念MHA(MasterHigh Availability)是一套优秀的MySQL高可用环境下故障切换和主从复制的软件.MHA 的出现就是解决MySQL 单点的问题.MySQL故障切换过程中 ...

  5. Windows难民安装docker的注意事项

    Windows下如何安装docker,这个没啥可说的,一直下一步就ok Windows  docker 下载地址: https://download.docker.com/win/stable/Doc ...

  6. python IO流操作

    python IO流操作 学习完本篇,你将会独立完成 实现操作系统中文件及文件目录的拷贝功能. 将目标图片拷贝到指定的目录中 实现一个自动阅卷程序, Right.txt保存正确答案,xx(学生姓名). ...

  7. vue项目实现文件下载进度条

    平时业务中下载文件方式常见的有俩种: 第一种,直接访问服务器的文件地址,自动下载文件: 第二种 ,服务器返回blob文件流,再对文件流进行处理和下载. 一般小文件适用于第一种下载方案,不占用过多服务器 ...

  8. 一起学习PHP的runkit扩展如何使用

    这次又为大家带来一个好玩的扩展.我们知道,在 PHP 运行的时候,也就是部署完成后,我们是不能修改常量的值,也不能修改方法体内部的实现的.也就是说,我们编码完成后,将代码上传到服务器,这时候,我们想在 ...

  9. Java基础系列(35)- 数组声明创建

    数组声明创建 首先必须声明数组变量,才能在程序中使用数组.下面是声明数组变量的语法: dataType[] arrayRefVar; //首选的方法 或 dataType arrayRefVar[]; ...

  10. requestAnimationFrame 切换页面问题

    requestAnimationFrame 切换页面时, 之前定时的内容还会继续执行. 所以 要注意处理动画函数内容,否则会出现死循环. 遇到的问题: 我在两个页面都有使用 requestAnimat ...