当前位置: 移动技术网 > IT编程>开发语言>.net > Ocelot简易教程(五)之集成IdentityServer认证以及授权

Ocelot简易教程(五)之集成IdentityServer认证以及授权

2018年10月18日  | 移动技术网IT编程  | 我要评论

异世之横行天下,纯种藏獒,pullup

ocelot简易教程目录

  1. ocelot简易教程(一)之ocelot是什么
  2. ocelot简易教程(二)之快速开始1
  3. ocelot简易教程(二)之快速开始2
  4. ocelot简易教程(三)之主要特性及路由详解
  5. ocelot简易教程(四)之请求聚合以及服务发现
  6. ocelot简易教程(五)之集成identityserver认证以及授权

    作者:依乐祝
    原文地址:

最近比较懒,所以隔了n天才来继续更新第五篇ocelot简易教程,本篇教程会先简单介绍下官方文档记录的内容然后在前几篇文档代码的基础上进行实例的演示。目的是为了让小白也能按照步骤把代码跑起来。当然,在开始之前你要对identityserver有一定的了解,并且能够进行identityserver的集成,如果你还不会集成identityserver的话还是先看看我的这篇asp.netcorewebapi图片上传接口(二)集成identityserver4授权访问(附源码)文章吧。里面有一步一步的集成identityserver的实例。

好了,废话说完了,那就让我们开始进入今天的主题吧!ocelot认证与授权。

概念表述

认证

为了验证reroutes并随后使用ocelot的任何基于声明的功能,例如授权或使用令牌中的值修改请求。 用户必须像往常一样在他们的startup.cs中注册认证服务,惟一的不同是他们需要给每个认证注册提供一个方案,例如

public void configureservices(iservicecollection services)
{
    var authenticationproviderkey = "ocelotkey";

    services.addauthentication()
        .addjwtbearer(authenticationproviderkey, x =>
        {
        });
}

在此示例中,ocelotkey是此提供程序已注册的方案。然后我们将其映射到配置中的reroute,例如

"reroutes": [
    {
      "downstreampathtemplate": "/api/{everything}",
      "downstreamscheme": "http",
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 1001
        },
        {
          "host": "localhost",
          "port": 1002
        }
      ],
      "upstreampathtemplate": "/{everything}",
      "upstreamhttpmethod": [ "get", "post" ],
      "loadbalanceroptions": {
        "type": "roundrobin"
      },
      "authenticationoptions": {
        "authenticationproviderkey": "ocelotkey",
        "allowedscopes": []
      }
    }
  ]

当ocelot运行时,它将查看此reroutes中 authenticationoptions节点下面的authenticationproviderkey并检查是否有使用给定密钥注册的身份验证提供程序。如果没有,那么ocelot不会启动,如果有的话reroute将在执行时使用该提供者。

如果对reroute进行了身份验证,则ocelot将在执行身份验证中间件时调用与其关联的认证方案。如果请求失败,则认证ocelot返回http的状态代码为401即未授权状态。

jwt令牌

如果您想使用jwt令牌进行身份验证,可能来自oauth之类的提供程序,您可以正常注册您的身份验证中间件,例如

public void configureservices(iservicecollection services)
{
    var authenticationproviderkey = "ocelotkey";

    services.addauthentication()
        .addjwtbearer(authenticationproviderkey, x =>
        {
            x.authority = "test";
            x.audience = "test";
        });

    services.addocelot();
}

然后将身份验证提供程序密钥映射到配置中的reroute,例如

"reroutes": [
    {
      "downstreampathtemplate": "/api/{everything}",
      "downstreamscheme": "http",
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 1001
        },
        {
          "host": "localhost",
          "port": 1002
        }
      ],
      "upstreampathtemplate": "/{everything}",
      "upstreamhttpmethod": [ "get", "post" ],
      "loadbalanceroptions": {
        "type": "roundrobin"
      },
      "authenticationoptions": {
        "authenticationproviderkey": "ocelotkey",
        "allowedscopes": []
      }
    }
  ]

identity server bearer tokens认证

接下来上今天的主角了。identityserver认证方式。为了使用identityserver承载令牌,请按照惯例在configureservices 中使用方案(密钥)注册您的identityserver服务。 如果您不明白如何操作,请访问identityserver文档。或者查看我的这篇asp.netcorewebapi图片上传接口(二)集成identityserver4授权访问(附源码)文章。

 var authenticationproviderkey = "ocelotkey";
            var identityserveroptions = new identityserveroptions();
            configuration.bind("identityserveroptions", identityserveroptions);
            services.addauthentication(identityserveroptions.identityscheme)
                .addidentityserverauthentication(authenticationproviderkey, options =>
                {
                    options.requirehttpsmetadata = false; //是否启用https
                    options.authority = $"http://{identityserveroptions.serverip}:{identityserveroptions.serverport}";//配置授权认证的地址
                    options.apiname = identityserveroptions.resourcename; //资源名称,跟认证服务中注册的资源列表名称中的apiresource一致
                    options.supportedtokens = supportedtokens.both;
                }
                );
            services.addocelot()//注入ocelot服务
                    .addconsul();

然后将身份验证提供程序密钥映射到配置中的reroute,例如

"reroutes": [
    {
      "downstreampathtemplate": "/api/{everything}",
      "downstreamscheme": "http",
      "downstreamhostandports": [
        {
          "host": "localhost",
          "port": 1001
        },
        {
          "host": "localhost",
          "port": 1002
        }
      ],
      "upstreampathtemplate": "/{everything}",
      "upstreamhttpmethod": [ "get", "post" ],
      "loadbalanceroptions": {
        "type": "roundrobin"
      },
      "authenticationoptions": {
        "authenticationproviderkey": "ocelotkey",
        "allowedscopes": []
      }
    }
  ]

允许访问的范围(allowed scopes)

如果将范围添加到allowedscopes,ocelot将获得类型范围的所有用户声明(从令牌中),并确保用户具有列表中的所有范围。

这是一种基于范围限制对reroute访问的方式。(我也没用过这种方式,感觉有点类似identityserver scope的概念)

实例演示集成identityserver

  1. 新建一个ocelotdemo.auth asp.net core web api项目

  2. 项目进行identityserver服务端相关的配置,这里为了演示的方便采用硬编码的方式进行的配置。具体配置可以参考asp.netcorewebapi图片上传接口(二)集成identityserver4授权访问(附源码)这篇文章

  3. 在网关项目ocelotdemo中添加nuget包

    install-package identityserver4.accesstokenvalidation   
  4. 在ocelotdemo项目中的startup.cs中加入identityserver验证,如下所示:

    var authenticationproviderkey = "ocelotkey";
                var identityserveroptions = new identityserveroptions();
                configuration.bind("identityserveroptions", identityserveroptions);
                services.addauthentication(identityserveroptions.identityscheme)
                    .addidentityserverauthentication(authenticationproviderkey, options =>
                    {
                        options.requirehttpsmetadata = false; //是否启用https
                        options.authority = $"http://{identityserveroptions.serverip}:{identityserveroptions.serverport}";//配置授权认证的地址
                        options.apiname = identityserveroptions.resourcename; //资源名称,跟认证服务中注册的资源列表名称中的apiresource一致
                        options.supportedtokens = supportedtokens.both;
                    }
                    );
                services.addocelot()//注入ocelot服务
                        .addconsul();
  5. 在ocelot.json中需要加入验证的reroute中,修改为如下的配置代码:

    "reroutes": [
        {
          "downstreampathtemplate": "/api/{everything}",
          "downstreamscheme": "http",
          "downstreamhostandports": [
            {
              "host": "localhost",
              "port": 1001
            },
            {
              "host": "localhost",
              "port": 1002
            }
          ],
          "upstreampathtemplate": "/{everything}",
          "upstreamhttpmethod": [ "get", "post" ],
          "loadbalanceroptions": {
            "type": "roundrobin"
          },
          "authenticationoptions": {
            "authenticationproviderkey": "ocelotkey",
            "allowedscopes": []
          }
        }
      ]
  6. 打开postman测试一下代码吧,首先访问一下http://www.lhsxpumps.com/_localhost:1000/values 这时候返回的结果是401未授权的状态,如下图所示:

    1539780575952

  7. 然后访问我们上面新建的identityserver服务器并获取token。如下图所示配置对应的参数进行获取:

    1539780272769

  8. 然后使用我们获取到的access_token进行ocelot网关接口的访问,如下所示进行配置:

    1539780805247

    可以看到结果返回了200代码,并且结果在good以及order之间进行切换。因为ocelot.json文件中对路由进行了roundrobin的负载均衡的策略。

授权

ocelot支持基于声明的授权,该授权在身份验证后运行。这意味着如果您有要授权的url,则可以将以下内容添加到reroute配置中。

"routeclaimsrequirement": {
    "usertype": "registered"
}

在此示例中,当调用授权中间件时,ocelot将检查用户是否具有声明类型usertype以及是否已注册该声明的值。如果不是,则用户将不被授权,并且将响应403禁止访问的状态码。

当然这种授权的方式在大部分业务场景中都是不适用的,需要自己重写ocelot的中间件才能实现。通过ocelot中间件的重写你可以实现自己的授权逻辑,如果你还有限流的需求,比如说对每个客户端进行不同的限流策略。比方说,有三个客户端a,b,c。访问相同的url,但是我们要控制a,每分钟只能访问10次,b每分钟能访问20次,而c不允许访问。针对这个场景ocelot却没有相关的实现。但是我们可以通过重写ocelot中间件来实现它。由于篇幅有限,所以今天就不进行介绍了。但是我会抽时间进行相关的实现,并分享给大家。

源码

本篇博文的源码已经上传到github。可以进行参考。https://github.com/yilezhu/ocelotdemo

总结

本文先大致介绍一下ocelot如何集成认证授权,然后通过实例进行了identityserver集成的演示,希望能对大家有一定的参考作用。当然文中也提到了,应对复杂的授权以及限流需要自行重写ocelot中间件进行实现。具体如何实现呢,我会尽快分享给大家。同样的通过重写ocelot中间件我们还可以把ocelot.json的配置信息存储到数据库并缓存到redis中!最后,感谢大家的阅读!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网