.Net Core使用Ocelot网关(二) -鉴权认证
前言
上一章已经简单的介绍了ocelot的使用了,但是网关暴露的接口如果什么人都能访问的话安全性就太低啦。所以我们需要去鉴权和认证。这里我们使用identityServer4给我们的网关来鉴权认证。
创建Identity服务
我们创建一个identity的服务来用于令牌的发放和鉴权。下图是我的项目结构。

Api_Gatewat端口:5000
Api_A端口:5001
Api_B端口:5002
IdentityServer端口:5003
通过nuget添加IdentityServer4的包,也可以通过程序包管理控制台执行以下命令Install-Package IdentityServer4。
添加一个Congif文件。
using System.Collections.Generic;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> GetIdentityResourceResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误
};
}
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
//可访问的API资源(资源名,资源描述)
return new List<ApiResource>
{
new ApiResource("Api_A", "Api_A"),
new ApiResource("Api_B", "Api_B")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client_a", //访问客户端Id,必须唯一
//使用客户端授权模式,客户端只需要clientid和secrets就可以访问对应的api资源。
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "Api_A",IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile }
},
new Client
{
ClientId = "client_b",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "Api_B",IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile }
}
};
}
}
}
添加两个API资源,并且添加两个客户端分别去访问不同资源。
在 Startup 中的 ConfigureServices 中配置IdentityServer服务。
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
在 Configure 中把IdentityServer放入http管道中。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
}
为ocelot集成Identity
通过nuget添加IdentityServer4.AccessTokenValidation的包,也可以通过程序包管理控制台执行以下命令 Install-Package IdentityServer4.AccessTokenValidation
IdentityServer4.AccessTokenValidation - 用于验证IdentityServer4中的JWT和引用令牌
在 Startup 的 ConfigureServices 中分别注册两个认证方案 Configure 中配置IdentityServer服务。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer("Api_A", i =>
{
i.Audience = "Api_A";
i.Authority = "http://localhost:5003";
i.RequireHttpsMetadata = false;
}).AddJwtBearer("Api_B", y =>
{
y.Audience = "Api_B";
y.Authority = "http://localhost:5003";
y.RequireHttpsMetadata = false;
});
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot();
app.UseAuthorization();
}
并修改ocelot配置文件,在Routes中添加授权信息
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/Api_A/{controller}/{action}",
"DownstreamPathTemplate": "/api/{controller}/{action}",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"RateLimitOptions": {
"ClientWhitelist": [ "127.0.0.1" ],
"EnableRateLimiting": true,
"Period": "1m",
"PeriodTimespan": 30,
"Limit": 5
},
"FileCacheOptions": {
"TtlSeconds": 5,
"Region": "time"
},
"UpstreamHeaderTransform": {
"demo": "a,b"
},
"DownstreamHeaderTransform": {
"demo": "xxxxxxx",
"Location": "{DownstreamBaseUrl},{BaseUrl}"
},
//授权信息
"AuthenticationOptions": {
"AuthenticationProviderKey": "Api_A",
"AllowedScopes": []
}
},
{
"UpstreamPathTemplate": "/Api_B/{controller}/{action}",
"DownstreamPathTemplate": "/api/{controller}/{action}",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5002
}
],
//授权信息
"AuthenticationOptions": {
"AuthenticationProviderKey": "Api_B",
"AllowedScopes": []
}
}
],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 20,
"TimeoutValue": 5000
},
"GlobalConfiguration": {
"RateLimitOptions": {
"DisableRateLimitHeaders": false,
"QuotaExceededMessage": "接口限流!",
"HttpStatusCode": 200,
"ClientIdHeader": "ClientId"
}
}
}
Ocelot会去检查ReRoutes是否配置了AuthenticationOptions节点。如果有会根据配置的认证方案进行身份认证。如果没有则不进行身份认证。
AuthenticationProviderKey 是刚才注册的认证方案。
AllowedScopes 是 AllowedScopes中配置的授权访问范围。
演示效果
我们为api_a和api_b分别注册了认证方案。如果我们不申请token是会401没有权限访问。

我们通过identityServer申请一个的token,并用它访问api_a和api_b。



可以看到我们申请的token是可以访问api_a的,但是不能访问api_b,因为client_a这个客户端只有访问api_a的权利。如果想访问api_b使用client_b申请token就可以啦。
总结
简单为Ocelot集成了IdentityServer,希望对大家有参考价值。如果文中有错误请联系我更改。
.Net Core使用Ocelot网关(二) -鉴权认证的更多相关文章
- 微服务网关Ocelot加入IdentityServer4鉴权-.NetCore(.NET5)中使用
Consul+Ocelot+Polly在.NetCore中使用(.NET5)-Consul服务注册,服务发现 Consul+Ocelot+Polly在.NetCore中使用(.NET5)-网关Ocel ...
- Spring Cloud Gateway + Jwt + Oauth2 实现网关的鉴权操作
Spring Cloud Gateway + Jwt + Oauth2 实现网关的鉴权操作 一.背景 二.需求 三.前置条件 四.项目结构 五.网关层代码的编写 1.引入jar包 2.自定义授权管理器 ...
- .Net Core使用Ocelot网关(一) -负载,限流,熔断,Header转换
1.什么是API网关 API网关是微服务架构中的唯一入口,它提供一个单独且统一的API入口用于访问内部一个或多个API.它可以具有身份验证,监控,负载均衡,缓存,请求分片与管理,静态响应处理等.API ...
- ASP.NET Core Authentication系列(二)实现认证、登录和注销
前言 在上一篇文章介绍ASP.NET Core Authentication的三个重要概念,分别是Claim, ClaimsIdentity, ClaimsPrincipal,以及claims-bas ...
- .net core在Ocelot网关中统一配置Swagger
最近在做微服务的时候,由于我们是采用前后端分离来开发的,提供给前端的直接是Swagger,如果Swagger分布在各个API中,前端查看Swagger的时候非常不便,因此,我们试着将Swagger集中 ...
- sip鉴权认证算法详解及python加密
1. 认证和加密 认证(Authorization)的作用在于表明自己是谁,即向别人证明自己是谁.而相关的概念是MD5,用于认证安全.注意MD5仅仅是个hash函数而已,并不是用于加密.因为ha ...
- RTSP鉴权认证之基础认证和摘要认证区别
RTSP认证类型 基本认证(basic authentication):http 1.0提出的认证方案,其消息传输不经过加密转换因此存在严重的安全隐患.: 摘要认证(digest authentica ...
- 庐山真面目之十二微服务架构基于Docker搭建Consul集群、Ocelot网关集群和IdentityServer版本实现
庐山真面目之十二微服务架构基于Docker搭建Consul集群.Ocelot网关集群和IdentityServer版本实现 一.简介 在第七篇文章<庐山真面目之七微服务架构Consul ...
- .Net Core微服务入门全纪录(七)——IdentityServer4-授权认证
前言 上一篇[.Net Core微服务入门全纪录(六)--EventBus-事件总线]中使用CAP完成了一个简单的Eventbus,实现了服务之间的解耦和异步调用,并且做到数据的最终一致性.这一篇将使 ...
随机推荐
- nyoj 74-小学生算术(进位问题)
74-小学生算术 内存限制:64MB 时间限制:3000ms 特判: No 通过数:23 提交数:53 难度:1 题目描述: 很多小学生在学习加法时,发现“进位”特别容易出错.你的任务是计算两个三位数 ...
- codeblocks 调试
codeblocks 调试工具使用的注意事项: 1.codebloccks 调试,必须要在一个项目下才可以,也就是说“单独的文件是不能运行debug工具的” 2.项目的目录文件名必须是全英文,同时文件 ...
- nyoj 366-D的小L (next_permutation())
366-D的小L 内存限制:64MB 时间限制:4000ms 特判: No 通过数:5 提交数:7 难度:2 题目描述: 一天TC的匡匡找ACM的小L玩三国杀,但是这会小L忙着哩,不想和匡 ...
- webpack安装与核心概念
安装webpack webpack核心概念:入口.输出.加载器.插件.模块.模式 一.安装webpack 1.安装webpack之前需要安装nodejs环境,在使用nodejs环境自带的包管理工具np ...
- supervisor服务
描述: 遇到各种各样的各种坑, 可以通过python2 的pip安装, 可以通过apt安装, 不支持python3: 如若用apt安装可能会自动启动并且加入开机自启(不保证成功),pip安装一定不会需 ...
- vue项目中使用百度统计
统计有多少人访问了自己的网站(wap端pc web端都适用),或者更细的统计网站每个页面的访问量,可以使用百度统计 百度统计传送门 按提示注册登录即可 登录后-->管理-->新增网站,配置 ...
- Pod镜像拉取策略imagePullPolicy
默认值是IfNotPresent Always 总是拉取: 首先获取仓库镜像信息, 如果仓库中的镜像与本地不同,那么仓库中的镜像会被拉取并覆盖本地. 如果仓库中的镜像与本地一致,那么不会拉取镜像. 如 ...
- Git之GitFlow工作流
一. GitFlow 介绍 1.1 什么是 GitFlow GitFlow 是一种 Git 工作流,它是团队成员遵守的一种代码管理方案 . 1.2 GitFlow 常用分支说明 分支名称 分支说明 P ...
- 小程序如何判断用户(后台使用Django)
小程序如何判断用户是哪个: 有Web开发经验的都知道,客户端用户发起请求,服务器收到请求后,可以通过把用户user_id记录到session里,然后下次通过session里面的user_id来辨别是哪 ...
- e = e || window.event的区别及用法
本文链接:https://blog.csdn.net/qq_41348029/article/details/81288481 e = e || window.event 在做事件处理时,用于区分IE ...