本文介绍Ocelot中的认证和授权(通过IdentityServer4),本文只使用最简单的IdentityServer,不会对IdentityServer4进行过多讲解。

1、Identity Server 4

(1)新建一个新的WebApi项目命名为IdentityServer,添加 IdentityServer4 Nuget包。
(2)添加Config类,添加如下代码:

public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>()
{
new ApiResource("api1", "My Api")
};
} public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes =
{
"api1"
}
}
};
}

(3)修改Startup中的ConfigureServices方法,添加如下代码:

services
.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());

修改Startup中的Config方法,在 app.UseMvc() 之前添加 app.UseIdentityServer()
(4)新建一个TokenController用于获取Token,代码如下:

[Produces("application/json")]
[Route("api/Token")]
public class TokenController : Controller
{
public async Task<JObject> Get()
{
var disco = await DiscoveryClient.GetAsync($"{Request.Scheme}://{Request.Host}");
if(disco.IsError)
{
Console.WriteLine(disco.Error);
return null;
} var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
if(tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return null;
} return tokenResponse.Json;
}
}

使用Postman请求http://localhost:6000/api/Token如下所示,可以获得一个token

 
token.png

至此,IdentityServer建立完成。

2、修改OcelotGetway

(1)修改Api网关项目中Startup中的ConfigureServices方法,添加IdentityServer认证:

services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication("TestKey", options =>
{
options.Authority = "http://localhost:6000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});

并在Configuration方法中添加 app.UseAuthentication();
(2)修改configuration.json
在上游请求路径为 /webapia/values 的路由配置中的配置项中添加

"AuthenticationOptions": {
"AuthenticationProviderKey": "TestKey",
"AllowScopes": []
}

注意:配置中的TestKey必须与添加IdentityServer认证时的 authenticationScheme 一致。
并添加一个获取Token的路由如下:

{
"DownstreamPathTemplate": "/api/Token",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6000
}],
"UpstreamPathTemplate": "/GetToken",
"UpstreamHttpMethod": [ "Get" ]
}

分别运行IdentityServer、OcelotGetway、WebApiA三个项目,然后使用Postman请求http://localhost:5000/webapia/values

 
unauthorized.png

可以看到提示未授权,
接着请求http://localhost:5000/GetToken获取token,并将token携带至上一个请求

 
authorized.png

可以看到正常请求到数据。
源码下载

完,下一篇介绍配置管理

作者:Weidaicheng
链接:https://www.jianshu.com/p/57d4d2fcec00
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

.Netcore 2.0 Ocelot Api网关教程(5)- 认证和授权的更多相关文章

  1. .Netcore 2.0 Ocelot Api网关教程(2)- 路由

    .Netcore 2.0 Ocelot Api网关教程(1) 路由介绍 上一篇文章搭建了一个简单的Api网关,可以实现简单的Api路由,本文介绍一下路由,即配置文件中ReRoutes,ReRoutes ...

  2. .Netcore 2.0 Ocelot Api网关教程(6)- 配置管理

    本文介绍Ocelot中的配置管理,配置管理允许在Api网关运行时动态通过Http Api查看/修改当前配置.由于该功能权限很高,所以需要授权才能进行相关操作.有两种方式来认证,外部Identity S ...

  3. .Netcore 2.0 Ocelot Api网关教程(7)- 限流

    本文介绍Ocelot中的限流,限流允许Api网关控制一段时间内特定api的总访问次数.限流的使用非常简单,只需要添加配置即可. 1.添加限流 修改 configuration.json 配置文件,对  ...

  4. .Netcore 2.0 Ocelot Api网关教程(4)- 服务发现

    本文介绍Ocelot中的服务发现(Service Discovery),Ocelot允许指定一个服务发现提供器,之后将从中寻找下游服务的host和port来进行请求路由.关于服务发现的详细介绍请点击. ...

  5. .Netcore 2.0 Ocelot Api网关教程(1)- 入门

    Ocelot(Github)Ocelot官方文档(英文)本文不会介绍Api网关是什么以及Ocelot能干什么需要对Api网关及Ocelot有一定的理论了解 开始使用Ocelot搭建一个入门级Api网关 ...

  6. .Netcore 2.0 Ocelot Api网关教程(10)- Headers Transformation

    本文介绍Ocelot中的请求头传递(Headers Transformation),其可以改变上游request传递给下游/下游response传递给上游的header. 1.修改ValuesCont ...

  7. .Netcore 2.0 Ocelot Api网关教程(9)- QoS

    本文介绍Ocelot中的QoS(Quality of Service),其使用了Polly对超时等请求下游失败等情况进行熔断. 1.添加Nuget包 添加 Ocelot.Provider.Polly  ...

  8. .Netcore 2.0 Ocelot Api网关教程(8)- 缓存

    Ocelot中使用 CacheManager 来支持缓存,官方文档中强烈建议使用该包作为缓存工具.以下介绍通过使用CacheManager来实现Ocelot缓存. 1.通过Nuget添加 Ocelot ...

  9. .Netcore 2.0 Ocelot Api网关教程(3)- 路由聚合

    在实际的应用当中,经常会遇到同一个操作要请求多个api来执行.这里先假设一个应用场景:通过姓名获取一个人的个人信息(性别.年龄),而获取每种个人信息都要调用不同的api,难道要依次调用吗?在Ocelo ...

随机推荐

  1. FFmpeg常用命令学习笔记(五)裁剪与合并命令

    裁剪与合并命令 1.音视频裁剪 ffmpeg -i input.mp4 -ss 00:01:00 -t 10 out.mp4 -ss:起始时间(HH:MM:SS).-t:裁剪时长(秒) 2.视频合并 ...

  2. Spring Boot 前期篇

    在学习springboot之前,学习一下Spring的java配置. 1. Spring的发展 1.1. Spring1.x 时代 在Spring1.x时代,都是通过xml文件配置bean,随着项目的 ...

  3. ES集群安装

    环境配置 安装openjdk(依赖) -openjdk.x86_64 安装elasticsearch yum -y install elasticsearch 配置 /etc/elasticsearc ...

  4. 开源笔记软件Joplin

    Joplin is a free, open source note taking and to-do application, which can handle a large number of ...

  5. PHP大文件分片上传

    前段时间做视频上传业务,通过网页上传视频到服务器. 视频大小 小则几十M,大则 1G+,以一般的HTTP请求发送数据的方式的话,会遇到的问题:1,文件过大,超出服务端的请求大小限制:2,请求时间过长, ...

  6. BZOJ 1706: [usaco2007 Nov]relays 奶牛接力跑 倍增Floyd

    题不难,但是一开始把读入看错了,调了半天qaq~ Code: #include <bits/stdc++.h> #define N 300 #define setIO(s) freopen ...

  7. [Luogu] 无线网络发射器选址

    https://www.luogu.org/problemnew/show/P2038 二维前缀和 #include <iostream> #include <cstdio> ...

  8. IVIEW组件的render方法在Table组件中的使用

    后端项目地址:https://gitee.com/wlovet/table-server 前端项目地址:  https://gitee.com/wlovet/table-project 一.Rende ...

  9. python 处理 json 四个函数dumps、loads、dump、load的区别

    1 .json.dumps() 函数是将一个 Python 数据类型列表(可以理解为字典)进行json格式的编码(转换成字符串,用于传播)eg, dict = {"age": &q ...

  10. 前端工程师需要掌握的 Babel 知识

    在前端圈子里,对于 Babel,大家肯定都比较熟悉了.如果哪天少了它,对于前端工程师来说肯定是个噩梦.Babel 的工作原理是怎样的可能了解的人就不太多了.本文将主要介绍 Babel 的工作原理以及怎 ...