首页 > 其他分享 >NetCore Ocelot 之 Authentication

NetCore Ocelot 之 Authentication

时间:2023-10-08 17:36:10浏览次数:35  
标签:Task return NetCore ctx Authentication Ocelot options IdentityServer4

In order to authenticate Routes and subsequently use any of Ocelot's claims based features such as authorization or modifying the request with values from the token. Users must register authentication services in their Startup.cs as usual but they provide a scheme(auhentication provider key) with each registration.e.g.

var authenticationProviderKey = "authenticationkey";
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(authenticationProviderKey, options =>
    {
        options.Authority = "https://localhost:9000";
        options.RequireHttpsMetadata = false;
        options.ApiName = "APIResource1";
        options.SupportedTokens = SupportedTokens.Both;
        options.JwtBearerEvents = new JwtBearerEvents  
        {
            OnChallenge = ctx => 
            {
                return Task.CompletedTask;
            },
            OnMessageReceived = ctx => 
            {
                var token = ctx.Token;
                return Task.CompletedTask;
            },
            OnTokenValidated = ctx => 
            {
                var securityToken = ctx.SecurityToken as JwtSecurityToken;
                var claimIdentities = ctx.Principal?.Identities;
                if (claimIdentities?.Any(i => i.Claims.Any(c=> c.Value.Equals("admin", StringComparison.OrdinalIgnoreCase))) ?? false)
                    ctx.Success();
                else
                    ctx.Fail("token validate failed.");
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = context =>
            {
                context.Fail(context.Exception);
                return Task.CompletedTask;
            },
            OnForbidden = context =>
            {
                context.Fail("403 forbidden");
                return Task.CompletedTask;
            }
        };
    });

In this example 'authenticationkey' is the scheme that this provider has been registered with. we then map this to a Route in the configuration e.g.

{
      "DownstreamPathTemplate": "/api/service1",
      "DownstreamScheme": "https",
      "DownstreamHttpMethod": "Get",
      "UpstreamHttpMethod": [ "Options", "Get", "Post", "Put", "Delete" ],
      "UpstreamPathTemplate": "/Ocelot/service1",
      //"UpstreamHost": "localhost",//404 Not found
      "UseServiceDiscovery": true,
      "ServiceName": "serviceA",
      /*
      LeastConnection
      RoundRobin
      NoLoadBalance
      */
      "LoadBalancerOptions": {
        "Type": "CustomRandomLoadBalancer"
      },
      "RateLimitOptions": {
        "ClientWhiteList": [ "NoLimitedAPI" ],
        "EnableRateLimiting": true,
        "Period": "10s", //1s, 5m, 1h, 1d
        "PeriodTimespan": 10, //retry after n second/seconds
        "Limit": 3
      },
      "authenticationoptions": {
        "authenticationproviderkey": "authenticationkey",
        "allowedscopes": [ "apiscope2" ]
      },
      "Key": "service1",
      "Priority": 11
    }

When Ocelot runs it will look at this Routes AuthenticationOptions.AuthenticationProviderKey and check that there is an Authentication provider registered with the given key. If there isn't then Ocelot will not start up, if there is then the Route will use that provider when it executes.

If a Route is authenticated Ocelot will invoke whatever scheme is associated with it while executing the authentication middleware. If the request fails authentication Ocelot returns a http status code 401/403.

Allowed Scopes

If you add scopes to AllowedScopes Ocelot will get all the user claims(from token) of the type scope and make sure that the user has all of the scopes in the list.

This is a way to restric access to a Route on a per scope basis.

IdentityServer4的配置请参考NetCore IdentityServer4,示例IdentityServer4获取的access token如下

{
  "nbf": 1696753665,
  "exp": 1696757265,
  "iss": "https://localhost:9000",
  "aud": [
    "APIResource1",
    "APIResource2"
  ],
  "client_id": "clientId",
  "client_role": "admin",
  "client_nickname": "tom",
  "client_Emai": "[email protected]",
  "jti": "5EA4ABD33903543E6C9F5151A517AF29",
  "iat": 1696753665,
  "scope": [
    "apiscope1",
    "apiscope2"
  ]
}

这里的aud即authentication middleware中Apiname所允许的API,scope即authenticationoptions.allowedscopes中指定所允许的scope。

如果authentication middleware中 apiname 配置非IdentityServer4 所允许的aud e.g.

options.Authority = "https://localhost:9000";
options.RequireHttpsMetadata = false;
options.ApiName = "APIResource3";
options.SupportedTokens = SupportedTokens.Both;

如果consul.json中配置authenticationoptions.allowedscopes为非IdentityServer4中允许apiscope e.g.

"authenticationoptions": {
        "authenticationproviderkey": "authenticationkey",
        "allowedscopes": [ "apiscope3" ]
      }

 如果配置均正确e.g.

 

 

标签:Task,return,NetCore,ctx,Authentication,Ocelot,options,IdentityServer4
From: https://www.cnblogs.com/qindy/p/17749687.html

相关文章

  • Mysql 8.0 Navicat连接Mysql报错Authentication plugin ‘caching_sha2_password‘ ca
    1、终端登陆MySQL$mysql-uroot-ppassword#登入mysql2、修改账户密码加密规则并更新用户密码ALTERUSER'root'@'localhost'IDENTIFIEDBY'123456'PASSWORDEXPIRENEVER;#修改加密规则ALTERUSER'root'@'localhost'IDENTIFIEDWITHmysql_nat......
  • NetCore Ocelot 之 Rate Limiting
    Ocelotsupportsratelimitingofupstreamrequestssothatyourdownstreamservicesdonotbecomeoverloaded.OKsotogetratelimitingworkingforaRouteyouneedtoaddthefollowingjsontoit."RateLimitOptions":{"ClientWhi......
  • NetCore学习笔记:单元测试和集成测试
    前言#我在使用AspNetCore的这段时间内,看了很多开源项目和博客,发现各种.Net体系的新技术很多人都有关注和使用,但却很少有人关注测试。测试是软件生命周期中的一个非常重要的阶段,对于保证软件的可靠性具有极其重要的意义。在应用程序的开发过程中,为了确保它的功能与预期一致,......
  • 开源.NetCore通用工具库Xmtool使用连载 - 扩展动态对象篇
    【Github源码】《上一篇》介绍了Xmtool工具库中的图形验证码类库,今天我们继续为大家介绍其中的扩展动态对象类库。<br>扩展动态对象是整个工具库中最重要的一个设计。在软件开发过程中,我们经常需要定义各种各样的数据对象;例如:用于参数传递的数据实体类、用于接口返回结果的Json......
  • AspNetCore不明确的匹配异常-请求与多个终结点匹配
    框架:net6.0AspNetCoreMVC添加区域控制器HomeController,直接启动报错;因默认路由下存在相同的控制器HomeController(非区域的),需要修改路由映射配置;在Program.cs添加区域路由配置app.MapAreaControllerRoute(name:"areaRoute",areaName:"Admin",pattern:......
  • SAP Commerce Cloud Backoffice site 里 Require Authentication 字段的作用
    “SAPCommerceCloudBackoffice”是一个用于管理和维护电子商务网站的强大工具,允许管理员和运营团队轻松地管理网站内容和配置。在Backoffice的WCMS(WebContentManagementSystem)部分,管理员可以创建、编辑和管理网站上的内容。在WCMS的Administration面板中,有一个字段称为Requ......
  • su: Authentication failure
    su:Authenticationfailurezonglin@zonglin-virtual-machine:~/Desktop$suPassword:su:Authenticationfailurezonglin@zonglin-virtual-machine:~/Desktop$sudopasswdrootNewpassword:BADPASSWORD:Thepasswordisshorterthan8charactersRetypenewpa......
  • .netCore 图形验证码,非System.Drawing.Common
    netcore需要跨平台,说白点就是放在windows服务器要能用,放在linux服务器上也能用,甚至macos上。很多时候需要使用到图形验证码,这就有问题了。旧方案1.引入包<PackageReferenceInclude="System.Drawing.Common"Version="5.0.3"/>2.添加引用usingSystem.Drawing;usingSystem......
  • SAP Commerce Cloud Backoffice site 里 Require Authentication 字段的作用
    “SAPCommerceCloudBackoffice”是一个用于管理和维护电子商务网站的强大工具,允许管理员和运营团队轻松地管理网站内容和配置。在Backoffice的WCMS(WebContentManagementSystem)部分,管理员可以创建、编辑和管理网站上的内容。在WCMS的Administration面板中,有一个字段称为Requi......
  • Mac Source Tree fatal: Authentication failed解决办法
    这种情况一般是用户名和密码时间太长,sourceTree自动给你过期了。1.先打开协同偏好设置-高级,把下图中的账号删除了然后你再次推送时,会提醒是输入用户名和密码2.在已经登录的git地址上,退出一下,重新返回登录页面,查看账号和密码就可以了直接在登录页面,把password的dom修改生tex......