本文介绍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. git log master..origin/master --oneline | wc -l 怎么知道本地仓库是不是最新的

    git log master..origin/master --oneline | wc -l 怎么知道本地仓库是不是最新的 git fetch   # 一定要先 fetch git log mast ...

  2. 2.Locust 跑起来试试

    代码 from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): @task def baidu(self): ...

  3. python之抽象类&abc模块+虚拟子类&register

    抽象类和接口: java 我们先从java讲起,没有java基础的可以略过. (挖坑) python 在python并没有抽象类之说,或者说抽象类=接口类(区别于接口) 继承有两种用途: 一:继承基类 ...

  4. 《Redis 设计与实现》读书笔记(二)

    单机数据库实现 九.数据库 1.服务器中的数据库 一个redis服务器保存多个数据库. struct redisServer { //一个数组,多个数据库 redisDb *db; } 当执行sele ...

  5. CF311B Cats Transport(斜率优化)

    题目描述 Zxr960115 是一个大农场主.他养了m只可爱的猫子,雇佣了p个铲屎官.这里有一条又直又长的道路穿过了农场,有n个山丘坐落在道路周围,编号自左往右从1到n.山丘i与山丘i-1的距离是Di ...

  6. Codeforces Round #591 (Div. 2, based on Technocup 2020 Elimination Round 1) D. Sequence Sorting

    链接: https://codeforces.com/contest/1241/problem/D 题意: You are given a sequence a1,a2,-,an, consistin ...

  7. PHP解决h5页面跨域

    前端h5 页面请求后端接口会出现跨域, PHP 只需三行代码即可解决 //解决前端跨域(h5页面) header("Access-Control-Allow-Origin:*"); ...

  8. siblings([expr])

    siblings([expr]) 概述 取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合.可以用可选的表达式进行筛选.大理石平台维修   参数 exprStringV1.0 用于筛选 ...

  9. PHP mysqli_insert_id() 函数

    定义和用法 mysqli_insert_id() 函数返回最后一个查询中自动生成的 ID(通过 AUTO_INCREMENT 生成). 语法 mysqli_insert_id(connection); ...

  10. Java进阶知识09 Hibernate一对多单向关联(Annotation+XML实现)

    1.Annotation 注解版 1.1.在一的一方加Set 1.2.创建Customer类和Order类 package com.shore.model; import java.util.Hash ...