本文介绍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. Redis数据类型操作说明

    List数据操作 lpush 语法:lpush key value [value…] 作用:将一个或多个值 value 插入到列表 key 的表头(最左边),从左边开始加入值,从左到右的顺序依次插入到 ...

  2. 【洛谷P2485】计算器

    BSGS模板题 代码如下 #include <bits/stdc++.h> using namespace std; typedef long long LL; LL fpow(LL a, ...

  3. CodeForces - 837E - Vasya's Function | Educational Codeforces Round 26

    /* CodeForces - 837E - Vasya's Function [ 数论 ] | Educational Codeforces Round 26 题意: f(a, 0) = 0; f( ...

  4. JS栈内存与堆内存

    ㈠JavaScript变量 ⒈分类 ⑴JavaScript中的变量分为基本类型和引用类型. ⑵基本类型就是保存在栈内存中的简单数据段. ⑶引用类型指的是那些保存在堆内存中的对象. ⒉基本类型  基本类 ...

  5. while循环与do. . . while循环语句

    ㈠导入 向页面中输出连续的数字 var n = 1; document.write(n++ +"<br />"); ㈡while循环 ⑴循环语句:通过循环语句可以反复的 ...

  6. Monkey实战测试步骤

    1,adb devices 确保设备在线 2,adb shell pm list packages 查看包名 3,adb shell monkey -p com.xzck.wangcai   --ig ...

  7. Luogu P4141 消失之物 背包 分治

    题意:给出$n$个物品的体积和最大背包容量$m$,求去掉一个物品$i$后,装满体积为$w\in [1,m]$背包的方案数. 有 N 个物品, 体积分别是 W1, W2, …, WN. 由于她的疏忽, ...

  8. SQL Server孤立用戶

    如何解决孤立用户问题 http://blog.csdn.net/zzl1120/article/details/7394468 SQL SERVER孤立用户问题解决方法 http://www.2cto ...

  9. Gym 100548F Color 给花染色 容斥+组合数学+逆元 铜牌题

    Problem F. ColorDescriptionRecently, Mr. Big recieved n flowers from his fans. He wants to recolor th ...

  10. 2018CCPC桂林站G Greatest Common Divisor

    题目描述 There is an array of length n, containing only positive numbers.Now you can add all numbers by ...