前言

上一章已经简单的介绍了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和引用令牌

StartupConfigureServices 中分别注册两个认证方案 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网关(二) -鉴权认证的更多相关文章

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

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

  2. Spring Cloud Gateway + Jwt + Oauth2 实现网关的鉴权操作

    Spring Cloud Gateway + Jwt + Oauth2 实现网关的鉴权操作 一.背景 二.需求 三.前置条件 四.项目结构 五.网关层代码的编写 1.引入jar包 2.自定义授权管理器 ...

  3. .Net Core使用Ocelot网关(一) -负载,限流,熔断,Header转换

    1.什么是API网关 API网关是微服务架构中的唯一入口,它提供一个单独且统一的API入口用于访问内部一个或多个API.它可以具有身份验证,监控,负载均衡,缓存,请求分片与管理,静态响应处理等.API ...

  4. ASP.NET Core Authentication系列(二)实现认证、登录和注销

    前言 在上一篇文章介绍ASP.NET Core Authentication的三个重要概念,分别是Claim, ClaimsIdentity, ClaimsPrincipal,以及claims-bas ...

  5. .net core在Ocelot网关中统一配置Swagger

    最近在做微服务的时候,由于我们是采用前后端分离来开发的,提供给前端的直接是Swagger,如果Swagger分布在各个API中,前端查看Swagger的时候非常不便,因此,我们试着将Swagger集中 ...

  6. sip鉴权认证算法详解及python加密

    1. 认证和加密    认证(Authorization)的作用在于表明自己是谁,即向别人证明自己是谁.而相关的概念是MD5,用于认证安全.注意MD5仅仅是个hash函数而已,并不是用于加密.因为ha ...

  7. RTSP鉴权认证之基础认证和摘要认证区别

    RTSP认证类型 基本认证(basic authentication):http 1.0提出的认证方案,其消息传输不经过加密转换因此存在严重的安全隐患.: 摘要认证(digest authentica ...

  8. 庐山真面目之十二微服务架构基于Docker搭建Consul集群、Ocelot网关集群和IdentityServer版本实现

    庐山真面目之十二微服务架构基于Docker搭建Consul集群.Ocelot网关集群和IdentityServer版本实现 一.简介      在第七篇文章<庐山真面目之七微服务架构Consul ...

  9. .Net Core微服务入门全纪录(七)——IdentityServer4-授权认证

    前言 上一篇[.Net Core微服务入门全纪录(六)--EventBus-事件总线]中使用CAP完成了一个简单的Eventbus,实现了服务之间的解耦和异步调用,并且做到数据的最终一致性.这一篇将使 ...

随机推荐

  1. uniapp打包Android APP

    1.uniAPP 将项目打包成,打包成功后格式如下 2.下载相关工具 Android studio(打包成app的工具) 和Hbuilder官方SDK,安装解压响应工具 3. 用 Android st ...

  2. "PSP助手”微信小程序宣传视频链接及内容介绍

    此作业的要求参见[https://edu.cnblogs.com/campus/nenu/2019fall/homework/8677] 队名:扛把子组 组长:迟俊文 组员:刘信鹏 韩昊 宋晓丽 梁梦 ...

  3. js 日常正则

    手机号 /^1((3[\d])|(4[5,6,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[1-3,5-8])|(9[1,8,9]))\d{8}$/ 大写字母 /^[A- ...

  4. Shell - 长 ping 脚本监控网络时延

    生产环境中, 网络时延是一个很重要的指标. 为了方便检查网络时延的大小, 我们可以通过ping命令实现长时间的网络监控. 1 ping 命令的使用 1.1 常用参数 -i: 每次执行ping操作的间隔 ...

  5. day 23 复习

    本来应该学习day23,由于上午未学习,下去困,导致今天未进行进度 那就做一下简单的复习吧! 1. while else结构,如果while 后的条件条件不再满足 引发循环再继续,则执行else中的内 ...

  6. mac系统下docker安装配置mysql详细步骤

    上文介绍了MacOS安装Docker傻瓜式教程,安装好后第一件事就决定把本地数据库迁移过来,那么首先就得安装mysql,下面就开始我们的安装之旅吧. 一.docker配置镜像加速器 我们使用docke ...

  7. CTF比赛时准备的一些shell命令

    防御策略: sudo service apache2 start :set fileformat=unix1.写脚本关闭大部分服务,除了ssh       2.改root密码,禁用除了root之外的所 ...

  8. https揭秘

    首先简要说明一下所谓的https证书是什么东西:打个比方,你第一次去银行办理业务的时候都需要手持本人身份中去办理业务,这个身份证从哪里来呢,没错,是从国家相关机关得来的,在中国内是通用的,类比到htt ...

  9. 使用Git上传文件到github

    第一次利用git连接github时往往都不会勾选Initialize this repository with a README,这样的的确确是简单了,但是如果我们需要勾选,勾选了之后应该怎么办呢?1 ...

  10. 在开发Thinkphp5.0智慧软文个人微信个人支付宝企业支付宝接口时遇到的坑

    在开发Thinkphp5.0智慧软文个人微信个人支付宝企业支付宝接口时遇到回调后提示成功但是不能自动充值的情况,现在记录一下: 两种情况 1.个人支付宝  个人微信遇到的情况 因为个人支付宝 个人微信 ...