本文介绍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. rac 数组之遍历

    rac的数组遍历其实很简单.但是有个点需要注意. 以下先举个例子说明遍历的用法 NSArray *temArr = @["]; [temArr.rac_sequence.signal sub ...

  2. kudu_cm_web安装

    [root@Node2 opt]# echo never > /sys/kernel/mm/transparent_hugepage/defrag[root@Node2 opt]# echo n ...

  3. [2019HDU多校第一场][HDU 6590][M. Code]

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6590 题目大意(来自队友):二维平面上有\(n\)个点,每个点要么是黑色要么是白色,问能否找到一条直线 ...

  4. Java中的集合List、ArrayList、Vector、Stack(三)

    List接口 List集合代表一个有序集合,集合中每一个元素都有其对应的顺序索引.List集合容许使用重复元素,可以通过索引来访问指定位置的集合对象. ArrayList和Vector实现类 Arra ...

  5. 4、docker镜像:花卷结构、commit镜像

    1.是什么 docker images 镜像是一种轻量级.可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含运行某个软件所需的所有内容,包括代码.运行时.库.环境变量和配置文件. ...

  6. poj1737

    Connected Graph POJ - 1737 An undirected graph is a set V of vertices and a set of E∈{V*V} edges.An ...

  7. codeforces723E

    One-Way Reform CodeForces - 723E There are n cities and m two-way roads in Berland, each road connec ...

  8. 简易的学生成绩管理系统(C++实现)

    最近浅显的学习了C++的基础知识,想来练练手,于是就用单链表写了最经典的小项目,存粹学习,所以就在控制台下写了,写的有点简陋,码了大概400多行. 下面上代码: #include <cstdli ...

  9. 发布web项目时,关于未能加载文件或程序集或它的某一个依赖项。拒绝访问的问题

    asp.net的程序是发布再iis上面的嘛,然后iis里面呢选中你的程序,在右边菜单有个编辑权限.然后添加权限Everyone.设置文件夹只读为否

  10. Django-安装/分组命名/路由分发

    一.安装Django 命令行窗口: pycharm安装: 二.创建Django项目 命令行窗口创建项目: 访问地址: 表示访问成功 注意如果我们在命令行窗口创建的应用需要我们手动的在django的se ...