前言

上一章已经简单的介绍了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. i7-9700也能安装Windows7

    商家说,i7-8700以上不支持Win7,只能安装Win10.我在手机网上也看过同样的说明,是微软与Intel联合行动,意在强迫用户升级到Win10.文章后面有,并不是不能装win7,是没有提供win ...

  2. C# XML解析之DOM模型

    DOM的工作方式是:首先将XML文档一次性的装入内存,然后根据文档中定义的元素和属性在内存中创建一个“树型结构”也就是一个文档对象模型,这里的含义其实是把文档对象化,文档中每个节点对应着模型中一个对象 ...

  3. IntelliJ IDEA使用报错

    GZIPResponseStream不是抽象的, 并且未覆盖javax.servlet.ServletOutputStream中 继承了某个抽象类, 或者 实现某个接口这时候你必须 把基类或接口中的所 ...

  4. GeoServer 查询sql视图

    说明: 最近项目中遇到一个需求,需要统计管网的长度,但管网数据量非常大,前端用openlayers接口统计直接就奔溃了. 后尝试使用调后台接口查数据库的方式,虽然可行但是又要多一层与后台交互的工作. ...

  5. 【论文阅读】A practical algorithm for distributed clustering and outlier detection

    文章提出了一种分布式聚类的算法,这是第一个有理论保障的考虑离群点的分布式聚类算法(文章里自己说的).与之前的算法对比有以下四个优点: 1.耗时短O(max{k,logn}*n), 2.传递信息规模小: ...

  6. linux用户资源控制

    /etc/security/limits.conf配置文件详解 这个文件主要是用来限制用户对资源的使用.是/lib64/security/pam_limits.so模块对应的/etc/serurity ...

  7. pymongo的基本操作和使用

    MongoDB简介 MongoDB是一个开源的文档类型数据库,它具有高性能,高可用,可自动收缩的特性.MongoDB能够避免传统的ORM映射从而有助于开发. 文档 在MongoDB中,一行纪录就是一个 ...

  8. day20191006假期作业收尾

    国庆作业:(轻重缓急,重点代码看懂理解了.每天重心就是代码,理解代码,理解,understand the code.花时间花功夫.只要功夫深,铁杵磨成针.) 一.使用DAO设计模式操作数据库CRUD( ...

  9. NPOI插件生成导出word文档

    因为之前没有接触NPOI过这个插件,所以几乎都是自己一边百度摸索一边学习. 这个插件对于Excel的数据导入和导出,可以说是很方便了, 但是对于导出word文档,可以说是很少的,百度了很多....也不 ...

  10. 程序员的进阶课-架构师之路(9)-平衡二叉树(AVL树)

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/m0_37609579/article/de ...