本文介绍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. python Pillow 图片处理模块,好强大有没有

    python Pillow 图片处理模块,好强大有没有 Pillow 需要给 python 另外安装 第一个用法:https://www.cnblogs.com/ibingshan/p/1105739 ...

  2. vuex直接修改state 与 用commit提交mutation来修改state的差异

    一. 使用vuex修改state时,有两种方式: 1)可以直接使用 this.$store.state.变量 = xxx;  2)this.$store.dispatch(actionType, pa ...

  3. 立即执行函数与For. . .in语句

    ㈠立即执行函数 ⑴定义:在函数定义完,立即被调用,这样的函数叫做立即执行函数 ⑵语法:函数对象() ⑶注意:立即执行函数往往只会执行一次 ⑷示例1: (function(){ alert(" ...

  4. Java数据库小项目01--实现用户登录注册

    先实现数据库和数据表,检测正常后再做其他的 CREATE TABLE users( username ) NOT NULL, PASSWORD ) NOT NULL); INSERT INTO use ...

  5. PHP mysqli_fetch_fields() 函数

    mysqli_fetch_fields() 函数返回结果集中代表字段(列)的对象的数组. 返回结果集中代表字段(列)的对象的数组,然后输出每个字段名称.表格和最大长度: <?php // 假定数 ...

  6. Spring@PostConstruct和@PreDestroy注解详解

    @PostConstruct注解使用 @PostConstructApi使用说明 The PostConstruct annotation is used on a method that needs ...

  7. useradd/usermod/userdel/passwd/groupadd/groupmod/groupdel/gpasswd

    用户 用户系统也是通过一个文件来管理的,默认的root用户id是0, shadow文件说明 加密算法类别 $后面的数字6指定了加密算法使用的是第六种,sha512加密 增加用户,修改成同样的密码,查看 ...

  8. Linux shell -"a-d"命令

    shell中条件判断if中的-z到-d的意思 分类:shellLinux (2006)  (0) shell中条件判断if中的-z到-d的意思  [ -a FILE ] 如果 FILE 存在则为真.  ...

  9. Selenium报错:StaleElementReferenceException

    一个学生在操作页面跳转时遇到一个Selenium报错, 如下图所示: StaleElementReferenceException: Message: stale element reference: ...

  10. 基础 Linux 命令速查清单

    jaywcjlove/linux-command: Linux命令大全搜索工具,内容包含Linux命令手册.详解.学习.搜集.https://git.io/linux  https://github. ...